<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三国战棋Roguelike</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#9D2932',      // 三国红
                        secondary: '#2D4262',    // 深蓝
                        neutral: '#E8C07D',      // 金色
                        dark: '#1C1C1C',         // 深色
                        light: '#F8F4E3'         // 浅色
                    },
                    fontFamily: {
                        sans: ['SimSun', 'serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .game-shadow {
                box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
            }
            .grid-cell {
                @apply w-14 h-14 border border-gray-300 flex items-center justify-center transition-all duration-200 relative;
            }
            .grid-cell-highlight {
                @apply bg-primary/20 cursor-pointer;
            }
            .grid-cell-move {
                @apply bg-blue-100 ring-2 ring-blue-500 cursor-pointer;
            }
            .grid-cell-attack {
                @apply bg-red-100 ring-2 ring-red-500 cursor-pointer;
            }
            .grid-cell-ability {
                @apply bg-purple-100 ring-2 ring-purple-500 cursor-pointer;
            }
            .character {
                @apply w-12 h-12 rounded-full flex items-center justify-center text-white font-bold transition-all duration-300 shadow-md relative cursor-pointer;
            }
            .character-selected {
                @apply scale-110 ring-4 ring-yellow-400 z-10;
            }
            .character-hurt {
                animation: hurt 0.5s;
            }
            .character-moving {
                animation: move 0.3s;
            }
            .character-dying {
                animation: die 1s forwards;
            }
            .btn-game {
                @apply bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/80 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary/50 transform hover:scale-105 active:scale-95;
            }
            .damage-indicator {
                position: absolute;
                color: #dc2626;
                font-weight: bold;
                pointer-events: none;
                animation: float-up 1s forwards;
            }
            .heal-indicator {
                position: absolute;
                color: #16a34a;
                font-weight: bold;
                pointer-events: none;
                animation: float-up 1s forwards;
            }
            .notification {
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                padding: 10px 20px;
                background-color: rgba(0, 0, 0, 0.8);
                color: white;
                border-radius: 5px;
                z-index: 100;
                opacity: 0;
                transition: opacity 0.3s;
            }
            .notification.show {
                opacity: 1;
            }
            .tooltip {
                position: absolute;
                background-color: rgba(0, 0, 0, 0.9);
                color: white;
                padding: 8px 12px;
                border-radius: 4px;
                font-size: 13px;
                z-index: 50;
                pointer-events: none;
                opacity: 0;
                transition: opacity 0.2s, transform 0.2s;
                transform: translateY(5px);
                white-space: nowrap;
                box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
                max-width: 300px;
                white-space: normal;
            }
            .tooltip.show {
                opacity: 1;
                transform: translateY(0);
            }
            .event-popup {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
                z-index: 1000;
                max-width: 80%;
                width: 400px;
            }
            .event-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.7);
                z-index: 999;
            }
            .perk {
                @apply bg-gray-100 p-3 rounded-md mb-2 cursor-pointer hover:bg-gray-200 transition-colors border-l-4 border-primary;
            }
            .loading-screen {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: #F8F4E3;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                z-index: 2000;
            }
            .loading-spinner {
                width: 50px;
                height: 50px;
                border: 5px solid #E8C07D;
                border-top: 5px solid #9D2932;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-bottom: 20px;
            }
            .status-icon {
                @apply absolute w-4 h-4 rounded-full flex items-center justify-center text-[8px] font-bold;
            }
            .ability-range-indicator {
                position: absolute;
                background-color: rgba(168, 85, 247, 0.3);
                border: 1px dashed #9333ea;
                pointer-events: none;
                transition: all 0.2s;
                z-index: 5;
            }
            .move-confirmation {
                position: absolute;
                background-color: white;
                border-radius: 5px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
                padding: 8px;
                z-index: 20;
                display: flex;
                gap: 5px;
            }
        }

        @keyframes hurt {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(0.8) rotate(5deg); background-color: #ef4444; }
        }
        
        @keyframes move {
            0% { transform: scale(0.8); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }
        
        @keyframes float-up {
            0% { transform: translateY(0); opacity: 1; }
            100% { transform: translateY(-30px); opacity: 0; }
        }
        
        @keyframes die {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2) rotate(10deg); }
            100% { transform: scale(0); opacity: 0; }
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 滚动条美化 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
        
        /* 自定义鼠标指针 */
        #game-map {
            cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%239D2932' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z'%3E%3C/path%3E%3C/svg%3E") 12 12, auto;
        }
        
        /* 防止页面元素被选中 */
        * {
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }
        
        input, textarea {
            user-select: text;
            -webkit-user-select: text;
            -moz-user-select: text;
            -ms-user-select: text;
        }
    </style>
</head>

<body class="bg-light min-h-screen font-sans">
    <!-- 加载屏幕 -->
    <div id="loading-screen" class="loading-screen">
        <div class="loading-spinner"></div>
        <h2 class="text-primary text-xl font-bold">加载游戏资源中...</h2>
        <p id="loading-status" class="text-gray-600 mt-2">初始化音效系统...</p>
    </div>

    <!-- 通知提示 -->
    <div id="notification" class="notification"></div>

    <!-- 事件弹窗 -->
    <div id="event-overlay" class="event-overlay hidden"></div>
    <div id="event-popup" class="event-popup hidden">
        <h3 id="event-title" class="text-xl font-bold text-primary mb-3"></h3>
        <p id="event-description" class="mb-4"></p>
        <div id="event-choices" class="space-y-2"></div>
    </div>

    <!-- 技能范围指示器容器 -->
    <div id="ability-indicators-container" class="absolute pointer-events-none z-10"></div>

    <!-- 移动确认对话框 -->
    <div id="move-confirmation" class="move-confirmation hidden"></div>

    <div class="container mx-auto p-4 max-w-6xl">
        <!-- 游戏标题 -->
        <header class="text-center my-6">
            <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-primary tracking-wide">
                <span class="relative inline-block">
                    三国战棋
                    <span class="absolute -bottom-1 left-0 w-full h-1 bg-neutral rounded-full"></span>
                </span>
                <span class="text-secondary ml-2">Roguelike</span>
            </h1>
            <p class="text-gray-600 mt-3 italic">随机地图 · 策略战斗 · 武将养成 · 永久死亡</p>
        </header>

        <!-- 游戏状态面板 -->
        <div class="flex flex-col md:flex-row justify-between mb-6 gap-4">
            <div
                class="bg-white rounded-lg p-4 game-shadow flex-1 transform transition-all duration-300 hover:shadow-lg">
                <h2 class="text-lg font-bold text-secondary flex items-center">
                    <i class="fa fa-map-signs mr-2"></i>当前关卡: <span id="level"
                        class="ml-1 font-bold text-primary">1</span>
                </h2>
                <p class="text-gray-600 mt-1">剩余敌人: <span id="enemy-count" class="font-bold text-red-500">3</span></p>
                <div class="mt-2 w-full bg-gray-200 rounded-full h-2.5">
                    <div id="level-progress" class="bg-primary h-2.5 rounded-full" style="width: 0%"></div>
                </div>
                <p class="text-xs text-gray-500 mt-1">距离下一关: <span id="progress-text">0%</span></p>
            </div>

            <div
                class="bg-white rounded-lg p-4 game-shadow flex-1 transform transition-all duration-300 hover:shadow-lg">
                <h2 class="text-lg font-bold text-secondary flex items-center">
                    <i class="fa fa-user mr-2"></i>我方武将
                </h2>
                <div id="player-party" class="flex flex-wrap gap-2 mt-2">
                    <!-- 武将状态会动态更新 -->
                </div>
            </div>
        </div>

        <!-- 游戏主区域 -->
        <div class="flex flex-col lg:flex-row gap-6">
            <!-- 游戏地图 -->
            <div
                class="flex-1 bg-white rounded-lg p-4 game-shadow transform transition-all duration-300 hover:shadow-lg relative">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="font-bold text-secondary flex items-center">
                        <i class="fa fa-map mr-2"></i>战场地图
                    </h2>
                    <div id="turn-indicator" class="px-3 py-1 bg-primary text-white text-sm rounded-full">
                        玩家回合
                    </div>
                </div>
                <div id="game-map" class="grid grid-cols-10 gap-0 mx-auto w-fit relative"></div>

                <!-- 操作提示 -->
                <div class="mt-4 p-2 bg-gray-100 rounded text-sm text-gray-600">
                    <p><i class="fa fa-keyboard-o mr-1"></i> 快捷键: <kbd
                            class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">M</kbd> 移动 <kbd
                            class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">A</kbd> 攻击 <kbd
                            class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">S</kbd> 技能 <kbd
                            class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">E</kbd> 结束回合</p>
                </div>
            </div>

            <!-- 游戏信息与控制 -->
            <div
                class="lg:w-80 bg-white rounded-lg p-4 game-shadow transform transition-all duration-300 hover:shadow-lg">
                <h2 class="text-lg font-bold text-secondary mb-4 flex items-center">
                    <i class="fa fa-info-circle mr-2"></i>游戏信息
                </h2>

                <div id="selected-info"
                    class="mb-6 p-3 bg-gray-100 rounded min-h-[100px] flex items-center justify-center">
                    <p class="text-gray-500">请选择一个角色或格子</p>
                </div>

                <div class="space-y-3">
                    <button id="move-btn" class="btn-game w-full flex items-center justify-center">
                        <i class="fa fa-arrows mr-2"></i>移动 (M)
                    </button>
                    <button id="attack-btn" class="btn-game w-full flex items-center justify-center bg-red-600">
                        <i class="fa fa-crosshairs mr-2"></i>攻击 (A)
                    </button>
                    <button id="ability-btn" class="btn-game w-full flex items-center justify-center bg-purple-600">
                        <i class="fa fa-bolt mr-2"></i>技能 (S)
                    </button>
                    <button id="end-turn-btn" class="btn-game w-full flex items-center justify-center bg-secondary">
                        <i class="fa fa-clock-o mr-2"></i>结束回合 (E)
                    </button>
                    <button id="new-game-btn"
                        class="btn-game w-full flex items-center justify-center bg-green-600 mt-4">
                        <i class="fa fa-refresh mr-2"></i>新游戏
                    </button>
                </div>

                <div class="mt-6 pt-4 border-t border-gray-200">
                    <h3 class="font-bold text-secondary mb-2">游戏说明</h3>
                    <ul class="text-sm text-gray-600 space-y-1">
                        <li><i class="fa fa-circle text-xs text-primary mr-1"></i> 红色: 我方武将</li>
                        <li><i class="fa fa-circle text-xs text-red-500 mr-1"></i> 敌军</li>
                        <li><i class="fa fa-circle text-xs text-yellow-500 mr-1"></i> 物品/道具</li>
                        <li><i class="fa fa-circle text-xs text-blue-500 mr-1"></i> 特殊事件</li>
                        <li><i class="fa fa-circle text-xs text-gray-400 mr-1"></i> 障碍物</li>
                    </ul>
                </div>

                <div class="mt-6 pt-4 border-t border-gray-200">
                    <h3 class="font-bold text-secondary mb-2 flex items-center">
                        <i class="fa fa-volume-up mr-2"></i>音效控制
                    </h3>
                    <div class="flex items-center">
                        <button id="toggle-sound" class="text-gray-600 hover:text-primary transition-colors">
                            <i class="fa fa-volume-up text-xl"></i>
                        </button>
                        <input type="range" id="volume-control" min="0" max="100" value="70"
                            class="ml-3 w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                    </div>
                    <button id="test-sound" class="mt-2 text-sm text-primary hover:underline">测试音效</button>
                </div>
            </div>
        </div>

        <!-- 游戏日志 -->
        <div class="mt-6 bg-white rounded-lg p-4 game-shadow transform transition-all duration-300 hover:shadow-lg">
            <h2 class="text-lg font-bold text-secondary mb-2 flex items-center">
                <i class="fa fa-history mr-2"></i>战斗日志
            </h2>
            <div id="game-log" class="h-32 overflow-y-auto text-sm text-gray-700 bg-gray-50 p-3 rounded"></div>
        </div>
    </div>

    <script>
        // 音效管理 - 修复声音问题
        const SoundManager = {
            sounds: {
                move: new Audio('../sound/move.mp3'),
                attack: new Audio('../sound/attack.mp3'),
                hit: new Audio('../sound/hit.mp3'),
                heal: new Audio('../sound/heal.mp3'),
                victory: new Audio('../sound/victory.mp3'),
                defeat: new Audio('../sound/defeat.mp3'),
                select: new Audio('../sound/select.mp3'),
                turn: new Audio('../sound/turn.mp3'),
                levelup: new Audio('../sound/levelup.mp3'),
                item: new Audio('../sound/item.mp3'),
                event: new Audio('../sound/event.mp3'),
                ability: new Audio('../sound/ability.mp3'),
            },
            music: new Audio('../sound/open.mp3'),
            soundEnabled: true,
            musicEnabled: true,
            volume: 0.7,
            loadStatus: 0,
            totalSounds: 0,
            loadAttempts: {}, // 跟踪每个音效的加载尝试次数

            init() {
                // 计算总音效数量
                this.totalSounds = Object.keys(this.sounds).length + 1; // +1 是背景音乐
                this.loadStatus = 0;
                this.loadAttempts = {};

                // 初始化加载尝试次数
                Object.keys(this.sounds).forEach(key => {
                    this.loadAttempts[key] = 0;
                });
                this.loadAttempts['music'] = 0;

                // 为每个音效添加加载完成事件
                Object.entries(this.sounds).forEach(([key, sound]) => {
                    this.setupSound(sound, key);
                });

                // 设置背景音乐
                this.setupSound(this.music, 'music', true);

                // 添加音量控制事件
                document.getElementById('volume-control').addEventListener('input', (e) => {
                    this.setVolume(e.target.value / 100);
                });

                // 添加音效开关事件
                document.getElementById('toggle-sound').addEventListener('click', () => {
                    this.toggleSound();
                });

                // 添加音效测试按钮
                document.getElementById('test-sound').addEventListener('click', () => {
                    this.testAllSounds();
                });

                // 添加用户交互时的声音初始化，解决自动播放限制
                document.body.addEventListener('click', () => {
                    if (this.soundEnabled) {
                        this.playMusic();
                    }
                }, { once: true });
            },

            setupSound(sound, key, isMusic = false) {
                sound.volume = isMusic ? this.volume * 0.3 : this.volume;
                sound.preload = 'auto';

                // 监听加载事件，更新加载状态
                const onLoad = () => {
                    this.loadStatus++;
                    this.updateLoadingScreen();
                };

                // 处理加载错误并重试
                const onError = (e) => {
                    console.error(`音效加载错误 (${key}):`, e);
                    this.loadAttempts[key]++;

                    // 最多重试3次
                    if (this.loadAttempts[key] < 3) {
                        console.log(`重试加载音效 (${key})，第${this.loadAttempts[key]}次`);
                        setTimeout(() => {
                            sound.load();
                        }, 1000 * this.loadAttempts[key]);
                    } else {
                        console.error(`音效${key}多次加载失败，已放弃`);
                        this.loadStatus++;
                        this.updateLoadingScreen();
                    }
                };

                sound.addEventListener('canplaythrough', onLoad, { once: true });
                sound.addEventListener('error', onError, { once: true });

                // 开始加载
                try {
                    sound.load();
                } catch (e) {
                    console.error(`加载音效${key}时出错:`, e);
                    onError(e);
                }
            },

            updateLoadingScreen() {
                const progress = Math.round((this.loadStatus / this.totalSounds) * 100);
                document.getElementById('loading-status').textContent = `加载资源: ${progress}%`;

                // 所有资源加载完成
                if (this.loadStatus >= this.totalSounds) {
                    setTimeout(() => {
                        document.getElementById('loading-screen').style.opacity = '0';
                        setTimeout(() => {
                            document.getElementById('loading-screen').style.display = 'none';
                            this.playMusic();
                        }, 500);
                    }, 500);
                }
            },

            setVolume(volume) {
                this.volume = volume;
                Object.values(this.sounds).forEach(sound => {
                    sound.volume = volume;
                });
                this.music.volume = volume * 0.3;
            },

            toggleSound() {
                this.soundEnabled = !this.soundEnabled;
                this.musicEnabled = !this.musicEnabled;

                const icon = document.querySelector('#toggle-sound i');
                if (this.soundEnabled) {
                    icon.classList.remove('fa-volume-off');
                    icon.classList.add('fa-volume-up');
                    this.playMusic();
                    showNotification('音效已开启');
                } else {
                    icon.classList.remove('fa-volume-up');
                    icon.classList.add('fa-volume-off');
                    this.music.pause();
                    showNotification('音效已关闭');
                }
            },

            play(soundName) {
                if (this.soundEnabled && this.sounds[soundName]) {
                    try {
                        // 克隆音频对象以允许同时播放同一音效
                        const sound = this.sounds[soundName].cloneNode();
                        sound.volume = this.volume;
                        sound.play().catch(e => {
                            console.log(`音频播放失败 (${soundName}):`, e);
                            // 如果因为未交互导致失败，尝试先触发一次交互
                            if (e.name === 'NotAllowedError') {
                                showNotification('请点击屏幕任意位置启用音效');
                                document.body.addEventListener('click', () => {
                                    sound.play().catch(err => console.log('仍无法播放音效:', err));
                                }, { once: true });
                            }
                        });
                    } catch (e) {
                        console.log('音频播放失败:', soundName, e);
                    }
                }
            },

            playMusic() {
                if (this.musicEnabled) {
                    try {
                        this.music.play().catch(e => {
                            console.log('背景音乐播放失败:', e);
                            if (e.name === 'NotAllowedError') {
                                showNotification('请点击屏幕任意位置启用背景音乐');
                            }
                        });
                    } catch (e) {
                        console.log('背景音乐播放失败:', e);
                    }
                }
            },

            testAllSounds() {
                showNotification('测试音效...');
                this.play('select');
                setTimeout(() => this.play('move'), 300);
                setTimeout(() => this.play('attack'), 600);
                setTimeout(() => this.play('hit'), 900);
                setTimeout(() => this.play('heal'), 1200);
                setTimeout(() => this.play('victory'), 1500);
                setTimeout(() => this.play('ability'), 1800);
            }
        };

        // 游戏配置
        const GAME_CONFIG = {
            mapSize: 10,          // 10x10的地图
            playerCount: 3,       // 初始玩家数量
            enemyCount: 3,        // 每关敌人数量
            obstacleRate: 0.15,   // 障碍物比例
            itemRate: 0.1,        // 物品比例
            eventRate: 0.05       // 事件比例
        };

        // 游戏状态
        const gameState = {
            level: 1,
            currentPlayer: 0,     // 当前操作的玩家索引
            selectedCell: null,   // 选中的格子
            selectedCharacter: null, // 选中的角色
            turn: 'player',       // 回合: player 或 enemy
            characters: [],       // 所有角色
            map: [],              // 地图数据
            levelProgress: 0,     // 关卡进度(0-100)
            gameOver: false,      // 游戏是否结束
            seed: Math.random(),  // 随机种子，用于生成地图
            activeAbility: null   // 当前激活的技能
        };

        // 角色类型
        const CHARACTER_TYPES = {
            PLAYER: 'player',
            ENEMY: 'enemy'
        };

        // 格子类型
        const CELL_TYPES = {
            EMPTY: 'empty',
            OBSTACLE: 'obstacle',
            ITEM: 'item',
            EVENT: 'event'
        };

        // 物品类型
        const ITEM_TYPES = {
            POTION: 'potion',
            WEAPON: 'weapon',
            ARMOR: 'armor',
            TREASURE: 'treasure',
            SCROLL: 'scroll'
        };

        // 事件类型
        const EVENT_TYPES = {
            MERCHANT: 'merchant',
            SHRINE: 'shrine',
            TREASURE_ROOM: 'treasure_room',
            AMBUSH: 'ambush',
            TRAINER: 'trainer',
            MYSTERY: 'mystery'
        };

        // 技能列表 - 增加范围信息
        const ABILITIES = {
            刘备: [
                { name: '仁德', description: '恢复周围友军10点生命值', cooldown: 3, range: 1, type: 'heal', target: 'ally' },
                { name: '义勇', description: '提升自身和相邻友军的防御力2回合', cooldown: 3, range: 1, type: 'buff', target: 'ally' }
            ],
            关羽: [
                { name: '青龙斩', description: '对单个敌人造成150%伤害', cooldown: 2, range: 1, type: 'damage', target: 'enemy' },
                { name: '忠义', description: '保护相邻的友军，承受他们受到的伤害', cooldown: 5, range: 1, type: 'buff', target: 'self' }
            ],
            张飞: [
                { name: '咆哮', description: '对周围所有敌人造成少量伤害并震慑他们', cooldown: 3, range: 1, type: 'damage', target: 'enemy' },
                { name: '破胆', description: '使单个敌人下一回合无法行动', cooldown: 4, range: 1, type: 'debuff', target: 'enemy' }
            ],
            曹操: [
                { name: '奸雄', description: '攻击后恢复自身造成伤害的30%', cooldown: 3, range: 0, type: 'passive', target: 'self' },
                { name: '号令', description: '提升周围友军的攻击力1回合', cooldown: 4, range: 1, type: 'buff', target: 'ally' }
            ],
            夏侯惇: [
                { name: '刚烈', description: '受到攻击时反弹20%伤害', cooldown: 3, range: 0, type: 'passive', target: 'self' },
                { name: '奋不顾身', description: '对敌人造成大量伤害，但自身也受到少量伤害', cooldown: 4, range: 1, type: 'damage', target: 'enemy' }
            ],
            典韦: [
                { name: '护主', description: '替相邻友军承受伤害', cooldown: 5, range: 1, type: 'buff', target: 'ally' },
                { name: '狂怒', description: '自身生命值越低，造成的伤害越高', cooldown: 0, range: 0, type: 'passive', target: 'self' }
            ]
        };

        // 初始化游戏
        function initGame() {
            // 清除所有提示和弹窗
            hideTooltip();
            hideEventPopup();
            clearAbilityIndicators();

            // 显示加载屏幕
            document.getElementById('loading-screen').style.display = 'flex';

            // 初始化音效系统
            SoundManager.init();

            // 重置游戏状态
            gameState.level = 1;
            gameState.gameOver = false;
            gameState.turn = 'player';
            gameState.seed = Math.random();
            gameState.activeAbility = null;

            generateMap();
            spawnCharacters();
            renderMap();
            updateGameInfo();
            updatePlayerPartyDisplay();
            addEventListeners();

            showNotification('欢迎来到三国战棋Roguelike！');
            logMessage('游戏开始！');
        }

        // 生成随机地图
        function generateMap() {
            gameState.map = [];
            gameState.levelProgress = 0;
            updateLevelProgress();

            // 使用种子确保随机数生成的一致性
            const seed = gameState.seed;
            let rand = mulberry32(seed);

            for (let y = 0; y < GAME_CONFIG.mapSize; y++) {
                const row = [];
                for (let x = 0; x < GAME_CONFIG.mapSize; x++) {
                    // 避免在玩家和敌人初始位置生成障碍物或事件
                    const isPlayerSpawnArea = (x < 3 && y < 3);
                    const isEnemySpawnArea = (x > 6 && y > 6);

                    if (isPlayerSpawnArea || isEnemySpawnArea) {
                        row.push({ type: CELL_TYPES.EMPTY });
                        continue;
                    }

                    // 随机生成内容
                    const r = rand();
                    if (r < GAME_CONFIG.obstacleRate) {
                        row.push({ type: CELL_TYPES.OBSTACLE });
                    } else if (r < GAME_CONFIG.obstacleRate + GAME_CONFIG.eventRate) {
                        // 随机事件
                        const eventTypes = Object.values(EVENT_TYPES);
                        const randomEvent = eventTypes[Math.floor(rand() * eventTypes.length)];
                        row.push({
                            type: CELL_TYPES.EVENT,
                            eventType: randomEvent
                        });
                    } else if (r < GAME_CONFIG.obstacleRate + GAME_CONFIG.eventRate + GAME_CONFIG.itemRate) {
                        // 随机物品
                        const itemTypes = Object.values(ITEM_TYPES);
                        const randomItem = itemTypes[Math.floor(rand() * itemTypes.length)];
                        row.push({
                            type: CELL_TYPES.ITEM,
                            itemType: randomItem
                        });
                    } else {
                        row.push({ type: CELL_TYPES.EMPTY });
                    }
                }
                gameState.map.push(row);
            }

            logMessage(`生成了第${gameState.level}关地图`);
        }

        // 生成角色
        function spawnCharacters() {
            gameState.characters = [];

            // 生成玩家角色（左上角）
            const playerPositions = [
                { x: 1, y: 1 },
                { x: 2, y: 1 },
                { x: 1, y: 2 }
            ];

            const playerNames = ['刘', '关', '张'];
            const playerColors = ['bg-primary', 'bg-secondary', 'bg-green-600'];
            const fullNames = ['刘备', '关羽', '张飞'];

            for (let i = 0; i < GAME_CONFIG.playerCount; i++) {
                // 根据关卡提升属性
                const levelBoost = (gameState.level - 1) * 10;

                // 随机属性波动，增加Roguelike随机性
                const hpVariance = Math.floor(Math.random() * 10) - 5;
                const attackVariance = Math.floor(Math.random() * 3) - 1;

                // 获取角色技能
                const abilities = ABILITIES[fullNames[i]].map(ability => ({
                    ...ability,
                    currentCooldown: 0
                }));

                gameState.characters.push({
                    id: `player-${i}`,
                    type: CHARACTER_TYPES.PLAYER,
                    name: playerNames[i],
                    fullName: fullNames[i],
                    color: playerColors[i],
                    x: playerPositions[i].x,
                    y: playerPositions[i].y,
                    hp: 100 + i * 20 + levelBoost + hpVariance,
                    maxHp: 100 + i * 20 + levelBoost + hpVariance,
                    attack: 10 + i * 5 + Math.floor(levelBoost / 3) + attackVariance,
                    defense: 5 + i * 2 + Math.floor(levelBoost / 5),
                    moved: false,
                    level: 1 + Math.floor((gameState.level - 1) / 3),
                    experience: 0,
                    nextLevelExp: 100 * (1 + Math.floor((gameState.level - 1) / 3)),
                    abilities: abilities,
                    statusEffects: [] // 状态效果
                });
            }

            // 生成敌人（右下角）
            // 根据关卡变化敌人类型和数量
            const enemyCount = Math.max(GAME_CONFIG.enemyCount, Math.floor(gameState.level / 2) + 2);
            const enemyPositions = [];

            // 随机生成敌人位置（右下角区域）
            while (enemyPositions.length < enemyCount) {
                const x = 7 + Math.floor(Math.random() * 3);
                const y = 7 + Math.floor(Math.random() * 3);

                // 检查位置是否已存在
                if (!enemyPositions.some(pos => pos.x === x && pos.y === y)) {
                    enemyPositions.push({ x, y });
                }
            }

            // 敌人类型池，随关卡增加更多种类
            const enemyTypes = [
                { names: ['曹', '曹操'], color: 'bg-red-500' },
                { names: ['夏侯', '夏侯惇'], color: 'bg-orange-500' },
                { names: ['典', '典韦'], color: 'bg-red-700' }
            ];

            // 高等级增加更强敌人
            if (gameState.level > 3) {
                enemyTypes.push(
                    { names: ['许', '许褚'], color: 'bg-red-600' },
                    { names: ['张', '张辽'], color: 'bg-indigo-600' }
                );
            }

            if (gameState.level > 5) {
                enemyTypes.push(
                    { names: ['吕', '吕布'], color: 'bg-purple-600' } // 更强的精英敌人
                );
            }

            for (let i = 0; i < enemyCount; i++) {
                // 随机选择敌人类型
                const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];

                // 根据关卡提升属性
                const levelBoost = (gameState.level - 1) * 10;

                // 精英敌人有额外属性加成
                const isElite = enemyType.names[1] === '吕布' || (gameState.level > 2 && Math.random() < 0.2);
                const eliteBoost = isElite ? 20 : 0;

                // 获取角色技能
                const abilities = ABILITIES[enemyType.names[1]] ?
                    ABILITIES[enemyType.names[1]].map(ability => ({
                        ...ability,
                        currentCooldown: 0
                    })) : [];

                gameState.characters.push({
                    id: `enemy-${i}`,
                    type: CHARACTER_TYPES.ENEMY,
                    name: enemyType.names[0],
                    fullName: enemyType.names[1],
                    color: enemyType.color,
                    x: enemyPositions[i].x,
                    y: enemyPositions[i].y,
                    hp: 80 + levelBoost + eliteBoost,
                    maxHp: 80 + levelBoost + eliteBoost,
                    attack: 8 + Math.floor(levelBoost / 3) + (isElite ? 5 : 0),
                    defense: 3 + Math.floor(levelBoost / 5) + (isElite ? 3 : 0),
                    isElite: isElite,
                    abilities: abilities,
                    statusEffects: [] // 状态效果
                });
            }
        }

        // 渲染地图
        function renderMap() {
            const mapContainer = document.getElementById('game-map');
            mapContainer.innerHTML = '';

            // 清除技能范围指示器
            clearAbilityIndicators();

            // 渲染每个格子
            for (let y = 0; y < GAME_CONFIG.mapSize; y++) {
                for (let x = 0; x < GAME_CONFIG.mapSize; x++) {
                    const cell = document.createElement('div');
                    cell.classList.add('grid-cell');
                    cell.dataset.x = x;
                    cell.dataset.y = y;

                    // 根据格子类型设置样式
                    const mapCell = gameState.map[y][x];
                    if (mapCell.type === CELL_TYPES.OBSTACLE) {
                        cell.classList.add('bg-gray-300');
                        cell.innerHTML = '<i class="fa fa-mountain text-gray-500"></i>';
                    } else if (mapCell.type === CELL_TYPES.ITEM) {
                        cell.classList.add('bg-yellow-100');
                        // 根据物品类型显示不同图标
                        switch (mapCell.itemType) {
                            case ITEM_TYPES.POTION:
                                cell.innerHTML = '<i class="fa fa-flask text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.WEAPON:
                                cell.innerHTML = '<i class="fa fa-sword text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.ARMOR:
                                cell.innerHTML = '<i class="fa fa-shield text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.TREASURE:
                                cell.innerHTML = '<i class="fa fa-diamond text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.SCROLL:
                                cell.innerHTML = '<i class="fa fa-scroll text-yellow-600"></i>';
                                break;
                        }
                    } else if (mapCell.type === CELL_TYPES.EVENT) {
                        cell.classList.add('bg-blue-100');
                        // 根据事件类型显示不同图标
                        switch (mapCell.eventType) {
                            case EVENT_TYPES.MERCHANT:
                                cell.innerHTML = '<i class="fa fa-shopping-cart text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.SHRINE:
                                cell.innerHTML = '<i class="fa fa-star text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.TREASURE_ROOM:
                                cell.innerHTML = '<i class="fa fa-chest text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.AMBUSH:
                                cell.innerHTML = '<i class="fa fa-crosshairs text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.TRAINER:
                                cell.innerHTML = '<i class="fa fa-graduation-cap text-blue-600"></i>';
                                break;
                            default:
                                cell.innerHTML = '<i class="fa fa-question text-blue-600"></i>';
                        }
                    }

                    // 检查是否有角色在这个格子上
                    const character = getCharacterAtPosition(x, y);
                    if (character) {
                        const charElement = document.createElement('div');
                        charElement.classList.add('character', character.color);
                        charElement.textContent = character.name;
                        charElement.title = `${character.fullName} (HP: ${character.hp}/${character.maxHp})`;
                        charElement.dataset.id = character.id;

                        // 精英敌人标记
                        if (character.isElite) {
                            const eliteMarker = document.createElement('div');
                            eliteMarker.classList.add('absolute', 'top-0', 'right-0', 'w-2', 'h-2', 'bg-yellow-300', 'rounded-full');
                            charElement.appendChild(eliteMarker);
                        }

                        // 添加状态效果图标
                        if (character.statusEffects && character.statusEffects.length > 0) {
                            character.statusEffects.forEach((effect, index) => {
                                const statusIcon = document.createElement('div');
                                statusIcon.classList.add('status-icon');

                                // 根据状态效果类型设置样式和图标
                                switch (effect.type) {
                                    case 'defense_up':
                                        statusIcon.classList.add('bg-blue-500');
                                        statusIcon.innerHTML = '<i class="fa fa-shield text-white text-[8px]"></i>';
                                        statusIcon.title = `防御提升 (剩余${effect.duration}回合)`;
                                        break;
                                    case 'attack_up':
                                        statusIcon.classList.add('bg-red-500');
                                        statusIcon.innerHTML = '<i class="fa fa-bolt text-white text-[8px]"></i>';
                                        statusIcon.title = `攻击提升 (剩余${effect.duration}回合)`;
                                        break;
                                    case 'stunned':
                                        statusIcon.classList.add('bg-gray-500');
                                        statusIcon.innerHTML = '<i class="fa fa-ban text-white text-[8px]"></i>';
                                        statusIcon.title = '被震慑 (无法行动)';
                                        break;
                                    case 'regeneration':
                                        statusIcon.classList.add('bg-green-500');
                                        statusIcon.innerHTML = '<i class="fa fa-plus text-white text-[8px]"></i>';
                                        statusIcon.title = '生命恢复 (每回合)';
                                        break;
                                }

                                // 定位多个状态图标
                                if (index === 0) {
                                    statusIcon.style.top = '0';
                                    statusIcon.style.left = '50%';
                                    statusIcon.style.transform = 'translateX(-50%)';
                                } else if (index === 1) {
                                    statusIcon.style.top = '50%';
                                    statusIcon.style.right = '0';
                                    statusIcon.style.transform = 'translateY(-50%)';
                                } else if (index === 2) {
                                    statusIcon.style.bottom = '0';
                                    statusIcon.style.left = '50%';
                                    statusIcon.style.transform = 'translateX(-50%)';
                                }

                                charElement.appendChild(statusIcon);
                            });
                        }

                        // 添加HP条
                        const hpBarContainer = document.createElement('div');
                        hpBarContainer.classList.add('absolute', 'bottom-0', 'left-0', 'w-full', 'h-1.5', 'px-0.5');

                        const hpBar = document.createElement('div');
                        hpBar.classList.add('h-full', 'rounded-sm', 'transition-all', 'duration-300');

                        // 根据HP比例设置颜色
                        const hpPercent = (character.hp / character.maxHp) * 100;
                        if (hpPercent > 70) {
                            hpBar.classList.add('bg-green-500');
                        } else if (hpPercent > 30) {
                            hpBar.classList.add('bg-yellow-500');
                        } else {
                            hpBar.classList.add('bg-red-500');
                        }

                        hpBar.style.width = `${hpPercent}%`;
                        hpBarContainer.appendChild(hpBar);
                        charElement.appendChild(hpBarContainer);

                        cell.appendChild(charElement);
                    }

                    // 如果是选中的格子，添加高亮
                    if (gameState.selectedCell && gameState.selectedCell.x === x && gameState.selectedCell.y === y) {
                        cell.classList.add('bg-blue-100', 'ring-2', 'ring-blue-500');
                    }

                    mapContainer.appendChild(cell);
                }
            }

            // 如果有选中的角色，高亮可行动的格子
            if (gameState.selectedCharacter && !gameState.selectedCharacter.moved && gameState.turn === 'player') {
                if (gameState.activeAbility) {
                    // 显示技能范围
                    highlightAbilityRange(gameState.selectedCharacter, gameState.activeAbility);
                } else {
                    // 显示移动和攻击范围
                    highlightSelectableCells(gameState.selectedCharacter);
                }
            }

            // 更新玩家状态显示
            updatePlayerPartyDisplay();
        }

        // 更新玩家队伍显示
        function updatePlayerPartyDisplay() {
            const container = document.getElementById('player-party');
            container.innerHTML = '';

            const players = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);

            players.forEach(player => {
                const charElement = document.createElement('div');
                charElement.classList.add('character', player.color, 'relative');
                charElement.textContent = player.name;

                // 构建详细信息文本
                let statusText = `${player.fullName} (等级: ${player.level})
HP: ${player.hp}/${player.maxHp}
攻击: ${player.attack} 防御: ${player.defense}`;

                // 添加临时属性加成
                const tempAttack = player.temporaryAttack || 0;
                const tempDefense = player.temporaryDefense || 0;
                if (tempAttack > 0 || tempDefense > 0) {
                    statusText += "\n临时加成:";
                    if (tempAttack > 0) statusText += ` 攻击+${tempAttack}`;
                    if (tempDefense > 0) statusText += ` 防御+${tempDefense}`;
                }

                // 添加状态效果
                if (player.statusEffects && player.statusEffects.length > 0) {
                    statusText += "\n状态:";
                    player.statusEffects.forEach(effect => {
                        switch (effect.type) {
                            case 'defense_up': statusText += " 防御提升"; break;
                            case 'attack_up': statusText += " 攻击提升"; break;
                            case 'stunned': statusText += " 被震慑"; break;
                            case 'regeneration': statusText += " 生命恢复"; break;
                        }
                    });
                }

                statusText += `\n经验: ${player.experience}/${player.nextLevelExp}`;
                charElement.title = statusText;

                // 等级标记
                const levelMarker = document.createElement('div');
                levelMarker.classList.add('absolute', 'top-0', 'left-0', 'text-[8px]', 'bg-black', 'text-white', 'px-1', 'rounded-sm');
                levelMarker.textContent = `Lv${player.level}`;
                charElement.appendChild(levelMarker);

                // 添加HP条
                const hpBarContainer = document.createElement('div');
                hpBarContainer.classList.add('absolute', 'bottom-0', 'left-0', 'w-full', 'h-1.5', 'px-0.5');

                const hpBar = document.createElement('div');
                hpBar.classList.add('h-full', 'rounded-sm');

                // 根据HP比例设置颜色
                const hpPercent = (player.hp / player.maxHp) * 100;
                if (hpPercent > 70) {
                    hpBar.classList.add('bg-green-500');
                } else if (hpPercent > 30) {
                    hpBar.classList.add('bg-yellow-500');
                } else {
                    hpBar.classList.add('bg-red-500');
                }

                hpBar.style.width = `${hpPercent}%`;
                hpBarContainer.appendChild(hpBar);
                charElement.appendChild(hpBarContainer);

                // 如果已经移动，添加标记
                if (player.moved) {
                    const movedIndicator = document.createElement('div');
                    movedIndicator.classList.add('absolute', 'top-0', 'right-0', 'w-3', 'h-3', 'bg-gray-400', 'rounded-full');
                    charElement.appendChild(movedIndicator);
                }

                container.appendChild(charElement);
            });
        }

        // 获取指定位置的角色
        function getCharacterAtPosition(x, y) {
            return gameState.characters.find(char => char.x === x && char.y === y);
        }

        // 添加事件监听器
        function addEventListeners() {
            // 移除已有的事件监听器，防止重复绑定
            const mapContainer = document.getElementById('game-map');
            const newMapContainer = mapContainer.cloneNode(true);
            mapContainer.parentNode.replaceChild(newMapContainer, mapContainer);

            // 重新获取引用
            const newMap = document.getElementById('game-map');

            // 地图格子点击事件
            newMap.addEventListener('click', handleCellClick);

            // 按钮事件
            document.getElementById('move-btn').addEventListener('click', handleMove);
            document.getElementById('attack-btn').addEventListener('click', handleAttack);
            document.getElementById('ability-btn').addEventListener('click', handleAbility);
            document.getElementById('end-turn-btn').addEventListener('click', endPlayerTurn);
            document.getElementById('new-game-btn').addEventListener('click', initGame);

            // 添加键盘快捷键
            document.addEventListener('keydown', (e) => {
                if (gameState.turn !== 'player' || gameState.gameOver) return;

                switch (e.key.toLowerCase()) {
                    case 'm': // 移动
                        handleMove();
                        e.preventDefault();
                        break;
                    case 'a': // 攻击
                        handleAttack();
                        e.preventDefault();
                        break;
                    case 's': // 技能
                        handleAbility();
                        e.preventDefault();
                        break;
                    case 'e': // 结束回合
                        endPlayerTurn();
                        e.preventDefault();
                        break;
                    case 'escape': // 取消选择
                        cancelSelection();
                        e.preventDefault();
                        break;
                }
            });

            // 鼠标悬停提示
            newMap.addEventListener('mousemove', handleMouseOver);
            newMap.addEventListener('mouseout', handleMouseOut);

            // 移动确认按钮事件
            const moveConfirmation = document.getElementById('move-confirmation');
            moveConfirmation.innerHTML = `
                <button id="confirm-move" class="bg-green-600 text-white p-2 rounded hover:bg-green-700">
                    <i class="fa fa-check"></i>
                </button>
                <button id="cancel-move" class="bg-red-600 text-white p-2 rounded hover:bg-red-700">
                    <i class="fa fa-times"></i>
                </button>
            `;

            document.getElementById('confirm-move').addEventListener('click', () => {
                if (gameState.selectedCharacter && gameState.selectedCell) {
                    // 执行实际移动
                    performMove(gameState.selectedCharacter, gameState.selectedCell.x, gameState.selectedCell.y);
                }
                hideMoveConfirmation();
            });

            document.getElementById('cancel-move').addEventListener('click', () => {
                hideMoveConfirmation();
            });
        }

        // 处理鼠标悬停 - 优化为单一提示
        function handleMouseOver(e) {
            // 隐藏任何现有的提示
            hideTooltip();

            const cell = e.target.closest('.grid-cell');
            if (!cell) return;

            const x = parseInt(cell.dataset.x);
            const y = parseInt(cell.dataset.y);

            // 检查这个格子是否有角色
            const character = getCharacterAtPosition(x, y);
            const mapCell = gameState.map[y][x];

            let tooltipText = `坐标: (${x}, ${y})`;

            if (character) {
                tooltipText = `<strong>${character.fullName}</strong>
HP: ${character.hp}/${character.maxHp}
攻击: ${character.attack}${character.temporaryAttack ? `(+${character.temporaryAttack})` : ''}
防御: ${character.defense}${character.temporaryDefense ? `(+${character.temporaryDefense})` : ''}`;

                // 添加状态效果
                if (character.statusEffects && character.statusEffects.length > 0) {
                    tooltipText += "\n状态:";
                    character.statusEffects.forEach(effect => {
                        let effectText = "";
                        switch (effect.type) {
                            case 'defense_up': effectText = `防御提升 (剩余${effect.duration}回合)`; break;
                            case 'attack_up': effectText = `攻击提升 (剩余${effect.duration}回合)`; break;
                            case 'stunned': effectText = '被震慑 (无法行动)'; break;
                            case 'regeneration': effectText = '生命恢复 (每回合)'; break;
                        }
                        tooltipText += `\n- ${effectText}`;
                    });
                }

                if (character.abilities && character.abilities.length > 0) {
                    tooltipText += "\n技能:";
                    character.abilities.forEach(ability => {
                        const cooldownText = ability.currentCooldown > 0 ? ` (冷却: ${ability.currentCooldown})` : "";
                        tooltipText += `\n- ${ability.name}: ${ability.description}${cooldownText}`;
                    });
                }
            } else if (mapCell.type === CELL_TYPES.ITEM) {
                let itemName = "";
                let itemDesc = "";
                switch (mapCell.itemType) {
                    case ITEM_TYPES.POTION:
                        itemName = "治疗药剂";
                        itemDesc = "恢复30-50点生命值";
                        break;
                    case ITEM_TYPES.WEAPON:
                        itemName = "精良武器";
                        itemDesc = "提升5-10点攻击力";
                        break;
                    case ITEM_TYPES.ARMOR:
                        itemName = "坚固防具";
                        itemDesc = "提升3-6点防御力";
                        break;
                    case ITEM_TYPES.TREASURE:
                        itemName = "宝藏";
                        itemDesc = "获得大量经验值";
                        break;
                    case ITEM_TYPES.SCROLL:
                        itemName = "魔法卷轴";
                        itemDesc = "重置技能冷却或提升属性";
                        break;
                }
                tooltipText = `${itemName}\n${itemDesc}`;
            } else if (mapCell.type === CELL_TYPES.EVENT) {
                let eventName = "";
                let eventDesc = "";
                switch (mapCell.eventType) {
                    case EVENT_TYPES.MERCHANT:
                        eventName = "商人";
                        eventDesc = "可以购买各种物品";
                        break;
                    case EVENT_TYPES.SHRINE:
                        eventName = "神社";
                        eventDesc = "可能获得祝福或诅咒";
                        break;
                    case EVENT_TYPES.TREASURE_ROOM:
                        eventName = "宝藏室";
                        eventDesc = "发现珍贵的宝藏";
                        break;
                    case EVENT_TYPES.AMBUSH:
                        eventName = "埋伏点";
                        eventDesc = "可能遭遇敌人埋伏";
                        break;
                    case EVENT_TYPES.TRAINER:
                        eventName = "训练师";
                        eventDesc = "可以提升某项属性";
                        break;
                    default:
                        eventName = "神秘事件";
                        eventDesc = "未知的奇遇";
                }
                tooltipText = `${eventName}\n${eventDesc}`;
            }

            // 创建提示框
            showTooltip(e.pageX, e.pageY, tooltipText);
        }

        // 显示提示框
        function showTooltip(x, y, text) {
            let tooltip = document.querySelector('.tooltip');
            if (!tooltip) {
                tooltip = document.createElement('div');
                tooltip.classList.add('tooltip');
                document.body.appendChild(tooltip);
            }

            tooltip.innerHTML = text.replace(/\n/g, '<br>');
            tooltip.style.left = `${x + 10}px`;
            tooltip.style.top = `${y + 10}px`;

            // 确保提示框不会超出屏幕
            const rect = tooltip.getBoundingClientRect();
            if (rect.right > window.innerWidth) {
                tooltip.style.left = `${x - rect.width - 10}px`;
            }
            if (rect.bottom > window.innerHeight) {
                tooltip.style.top = `${y - rect.height - 10}px`;
            }

            // 显示提示框
            setTimeout(() => {
                tooltip.classList.add('show');
            }, 100); // 延迟显示，避免快速移动时频繁出现
        }

        // 隐藏提示框
        function hideTooltip() {
            const tooltip = document.querySelector('.tooltip');
            if (tooltip) {
                tooltip.classList.remove('show');
            }
        }

        // 处理鼠标离开
        function handleMouseOut(e) {
            // 延迟隐藏，避免短暂离开时消失
            setTimeout(() => {
                const relatedTarget = e.relatedTarget;
                if (!relatedTarget || !relatedTarget.closest('#game-map')) {
                    hideTooltip();
                }
            }, 200);
        }

        // 处理格子点击
        function handleCellClick(e) {
            // 如果不是玩家回合或游戏结束，不能操作
            if (gameState.turn !== 'player' || gameState.gameOver) return;

            const cell = e.target.closest('.grid-cell');
            if (!cell) return;

            const x = parseInt(cell.dataset.x);
            const y = parseInt(cell.dataset.y);

            // 播放选择音效
            SoundManager.play('select');

            // 如果正在选择技能目标
            if (gameState.activeAbility && gameState.selectedCharacter) {
                const ability = gameState.activeAbility;
                const character = gameState.selectedCharacter;

                // 检查是否在技能范围内
                const distance = Math.max(Math.abs(x - character.x), Math.abs(y - character.y));
                if (distance > ability.range) {
                    showInfo(`目标超出${ability.name}的范围！`);
                    return;
                }

                // 检查目标是否符合技能要求
                const target = getCharacterAtPosition(x, y);
                let isValidTarget = false;

                if (ability.target === 'enemy' && target && target.type === CHARACTER_TYPES.ENEMY) {
                    isValidTarget = true;
                } else if (ability.target === 'ally' && target && target.type === CHARACTER_TYPES.PLAYER) {
                    isValidTarget = true;
                } else if (ability.target === 'self' && x === character.x && y === character.y) {
                    isValidTarget = true;
                } else if (ability.target === 'any' && (!target ||
                    (target.type === CHARACTER_TYPES.ENEMY && ability.canTargetEnemy) ||
                    (target.type === CHARACTER_TYPES.PLAYER && ability.canTargetAlly))) {
                    isValidTarget = true;
                }

                if (isValidTarget) {
                    selectCell(x, y);
                    useSelectedAbility();
                } else {
                    let targetType = "";
                    switch (ability.target) {
                        case 'enemy': targetType = "敌人"; break;
                        case 'ally': targetType = "友军"; break;
                        case 'self': targetType = "自己"; break;
                        case 'any': targetType = "任意目标"; break;
                    }
                    showInfo(`${ability.name}需要选择${targetType}作为目标！`);
                }

                return;
            }

            // 检查这个格子是否有角色
            const character = getCharacterAtPosition(x, y);

            // 如果点击了有角色的格子
            if (character) {
                // 只能选择己方角色
                if (character.type === CHARACTER_TYPES.PLAYER) {
                    selectCharacter(character, x, y);
                } else {
                    // 选中敌人，尝试攻击
                    if (gameState.selectedCharacter && !gameState.selectedCharacter.moved) {
                        selectCell(x, y);
                        // 自动尝试攻击
                        setTimeout(handleAttack, 300);
                    } else {
                        showInfo(`这是敌人: ${character.fullName} (HP: ${character.hp}/${character.maxHp})`);
                    }
                }
            }
            // 如果点击了事件格子
            else if (gameState.map[y][x].type === CELL_TYPES.EVENT) {
                if (gameState.selectedCharacter && !gameState.selectedCharacter.moved) {
                    // 检查是否在移动范围内
                    const distance = Math.max(Math.abs(x - gameState.selectedCharacter.x), Math.abs(y - gameState.selectedCharacter.y));
                    if (distance <= 2) {
                        selectCell(x, y);
                        // 先移动到事件格子，再触发事件
                        const oldX = gameState.selectedCharacter.x;
                        const oldY = gameState.selectedCharacter.y;

                        // 如果不在同一个格子，先移动
                        if (oldX !== x || oldY !== y) {
                            // 显示移动确认
                            showMoveConfirmation(x, y, () => {
                                gameState.selectedCharacter.x = x;
                                gameState.selectedCharacter.y = y;
                                gameState.selectedCharacter.moved = true;

                                logMessage(`${gameState.selectedCharacter.fullName}移动到了事件点`);
                                SoundManager.play('move');

                                renderMap();

                                // 移动后触发事件
                                setTimeout(() => {
                                    triggerEvent(x, y);
                                }, 500);
                            });
                        } else {
                            // 已经在事件格子上，直接触发
                            triggerEvent(x, y);
                        }
                    } else {
                        showInfo('距离太远，无法到达事件点');
                    }
                } else {
                    showInfo('请先选择一个未行动的己方武将');
                }
            }
            // 如果已经选中了角色，点击空格子
            else if (gameState.selectedCharacter && gameState.map[y][x].type !== CELL_TYPES.OBSTACLE) {
                selectCell(x, y);

                // 如果是物品格子，自动尝试移动过去
                if (gameState.map[y][x].type === CELL_TYPES.ITEM) {
                    // 显示移动确认
                    showMoveConfirmation(x, y);
                } else {
                    // 显示移动确认
                    showMoveConfirmation(x, y);
                }
            }
        }

        // 显示移动确认对话框
        function showMoveConfirmation(x, y, onConfirm = null) {
            const moveConfirmation = document.getElementById('move-confirmation');
            const cell = document.querySelector(`.grid-cell[data-x="${x}"][data-y="${y}"]`);

            if (cell) {
                // 定位确认框在格子上方
                const rect = cell.getBoundingClientRect();
                const mapRect = document.getElementById('game-map').getBoundingClientRect();

                moveConfirmation.style.left = `${rect.left - mapRect.left + rect.width / 2 - 25}px`;
                moveConfirmation.style.top = `${rect.top - mapRect.top - 40}px`;
                moveConfirmation.classList.remove('hidden');

                // 重新绑定确认事件，允许自定义回调
                const confirmBtn = document.getElementById('confirm-move');
                const originalOnClick = confirmBtn.onclick;

                confirmBtn.onclick = () => {
                    if (onConfirm) {
                        onConfirm();
                    } else if (gameState.selectedCharacter) {
                        performMove(gameState.selectedCharacter, x, y);
                    }
                    hideMoveConfirmation();
                    confirmBtn.onclick = originalOnClick; // 恢复原始事件
                };
            }
        }

        // 隐藏移动确认对话框
        function hideMoveConfirmation() {
            document.getElementById('move-confirmation').classList.add('hidden');
        }

        // 执行移动操作
        function performMove(character, x, y) {
            // 播放移动音效
            SoundManager.play('move');

            // 执行移动
            const oldX = character.x;
            const oldY = character.y;
            character.x = x;
            character.y = y;
            character.moved = true;

            // 更新关卡进度
            updateLevelProgress();

            // 检查是否有物品
            const cell = gameState.map[y][x];
            if (cell.type === CELL_TYPES.ITEM) {
                collectItem(character, cell);
                cell.type = CELL_TYPES.EMPTY; // 移除物品
            }

            logMessage(`${character.fullName}移动到了(${x}, ${y})`);

            // 先更新角色位置并添加移动动画
            const charElement = document.querySelector(`.character[data-id="${character.id}"]`);
            if (charElement) {
                charElement.classList.add('character-moving');

                // 动画结束后重新渲染地图
                setTimeout(() => {
                    renderMap();
                }, 300);
            } else {
                renderMap();
            }
        }

        // 选择角色
        function selectCharacter(character, x, y) {
            // 隐藏移动确认
            hideMoveConfirmation();

            // 取消任何激活的技能
            gameState.activeAbility = null;

            // 如果角色已经移动过，不能再操作
            if (character.moved) {
                showInfo(`${character.fullName}已经移动过了`);
                return;
            }

            gameState.selectedCharacter = character;
            gameState.selectedCell = { x, y };

            // 更新UI
            renderMap(); // 重新渲染以显示可行动格子

            // 显示角色详细信息
            let statusText = `<strong>${character.fullName}</strong> (等级: ${character.level})<br>
HP: ${character.hp}/${character.maxHp}<br>
攻击: ${character.attack}${character.temporaryAttack ? `(+${character.temporaryAttack})` : ''}<br>
防御: ${character.defense}${character.temporaryDefense ? `(+${character.temporaryDefense})` : ''}`;

            // 添加状态效果
            if (character.statusEffects && character.statusEffects.length > 0) {
                statusText += "<br>状态:";
                character.statusEffects.forEach(effect => {
                    let effectText = "";
                    switch (effect.type) {
                        case 'defense_up': effectText = `防御提升 (剩余${effect.duration}回合)`; break;
                        case 'attack_up': effectText = `攻击提升 (剩余${effect.duration}回合)`; break;
                        case 'stunned': effectText = '被震慑'; break;
                        case 'regeneration': effectText = '生命恢复'; break;
                    }
                    statusText += `<br>- ${effectText}`;
                });
            }

            let abilityText = "";
            if (character.abilities && character.abilities.length > 0) {
                abilityText = "<br>技能:";
                character.abilities.forEach(ability => {
                    const cooldownText = ability.currentCooldown > 0 ? ` (冷却: ${ability.currentCooldown})` : "";
                    abilityText += `<br>- ${ability.name}: ${ability.description}${cooldownText}`;
                });
            }

            showInfo(`${statusText}<br>经验: ${character.experience}/${character.nextLevelExp}${abilityText}`);

            // 高亮选中的角色
            const charElement = document.querySelector(`.character[data-id="${character.id}"]`);
            if (charElement) {
                charElement.classList.add('character-selected');
            }
        }

        // 选择格子
        function selectCell(x, y) {
            // 隐藏移动确认
            hideMoveConfirmation();

            gameState.selectedCell = { x, y };

            // 重新渲染地图以显示选中状态
            renderMap();

            // 检查是否是敌人
            const enemy = getCharacterAtPosition(x, y);
            if (enemy && enemy.type === CHARACTER_TYPES.ENEMY) {
                showInfo(`敌人: ${enemy.fullName} (HP: ${enemy.hp}/${enemy.maxHp})<br>攻击: ${enemy.attack} 防御: ${enemy.defense}`);
            } else {
                // 检查是否是物品
                const cell = gameState.map[y][x];
                if (cell.type === CELL_TYPES.ITEM) {
                    let itemName = "";
                    let itemDesc = "";
                    switch (cell.itemType) {
                        case ITEM_TYPES.POTION:
                            itemName = "治疗药剂";
                            itemDesc = "恢复30-50点生命值";
                            break;
                        case ITEM_TYPES.WEAPON:
                            itemName = "精良武器";
                            itemDesc = "提升5-10点攻击力";
                            break;
                        case ITEM_TYPES.ARMOR:
                            itemName = "坚固防具";
                            itemDesc = "提升3-6点防御力";
                            break;
                        case ITEM_TYPES.TREASURE:
                            itemName = "宝藏";
                            itemDesc = "获得大量经验值";
                            break;
                        case ITEM_TYPES.SCROLL:
                            itemName = "魔法卷轴";
                            itemDesc = "重置技能冷却或提升属性";
                            break;
                    }
                    showInfo(`物品: ${itemName}<br>${itemDesc}<br>(坐标: ${x}, ${y})`);
                } else if (cell.type === CELL_TYPES.EVENT) {
                    let eventName = "";
                    let eventDesc = "";
                    switch (cell.eventType) {
                        case EVENT_TYPES.MERCHANT:
                            eventName = "商人";
                            eventDesc = "可以购买各种物品";
                            break;
                        case EVENT_TYPES.SHRINE:
                            eventName = "神社";
                            eventDesc = "可能获得祝福或诅咒";
                            break;
                        case EVENT_TYPES.TREASURE_ROOM:
                            eventName = "宝藏室";
                            eventDesc = "发现珍贵的宝藏";
                            break;
                        case EVENT_TYPES.AMBUSH:
                            eventName = "埋伏点";
                            eventDesc = "可能遭遇敌人埋伏";
                            break;
                        case EVENT_TYPES.TRAINER:
                            eventName = "训练师";
                            eventDesc = "可以提升某项属性";
                            break;
                        default:
                            eventName = "神秘事件";
                            eventDesc = "未知的奇遇";
                    }
                    showInfo(`事件: ${eventName}<br>${eventDesc}<br>(坐标: ${x}, ${y})`);
                } else {
                    showInfo(`选中了格子 (${x}, ${y})`);
                }
            }
        }

        // 取消选择
        function cancelSelection() {
            gameState.selectedCharacter = null;
            gameState.selectedCell = null;
            gameState.activeAbility = null;
            hideMoveConfirmation();
            hideTooltip();
            renderMap();
            showInfo('请选择一个角色或格子');
        }

        // 高亮可移动的格子
        function highlightSelectableCells(character) {
            // 计算可移动范围（2格范围内）
            for (let dy = -2; dy <= 2; dy++) {
                for (let dx = -2; dx <= 2; dx++) {
                    // 不能原地不动
                    if (dx === 0 && dy === 0) continue;

                    const x = character.x + dx;
                    const y = character.y + dy;

                    // 检查是否在地图范围内
                    if (x >= 0 && x < GAME_CONFIG.mapSize && y >= 0 && y < GAME_CONFIG.mapSize) {
                        // 检查是否是障碍物
                        if (gameState.map[y][x].type !== CELL_TYPES.OBSTACLE) {
                            // 检查是否有其他角色
                            const targetChar = getCharacterAtPosition(x, y);
                            if (!targetChar) {
                                // 可移动的格子
                                const cell = document.querySelector(`.grid-cell[data-x="${x}"][data-y="${y}"]`);
                                if (cell) {
                                    cell.classList.add('grid-cell-move');

                                    // 添加移动提示
                                    if (!cell.querySelector('.move-indicator')) {
                                        const indicator = document.createElement('div');
                                        indicator.classList.add('move-indicator', 'text-xs', 'text-blue-600', 'opacity-70', 'absolute');
                                        indicator.textContent = '移动';
                                        cell.appendChild(indicator);
                                    }
                                }
                            } else if (targetChar.type === CHARACTER_TYPES.ENEMY) {
                                // 可攻击的敌人
                                const cell = document.querySelector(`.grid-cell[data-x="${x}"][data-y="${y}"]`);
                                const distance = Math.max(Math.abs(x - character.x), Math.abs(y - character.y));
                                if (distance <= 1 && cell) {
                                    cell.classList.add('grid-cell-attack');

                                    // 添加攻击提示
                                    if (!cell.querySelector('.attack-indicator')) {
                                        const indicator = document.createElement('div');
                                        indicator.classList.add('attack-indicator', 'text-xs', 'text-red-600', 'opacity-70', 'absolute');
                                        indicator.textContent = '攻击';
                                        cell.appendChild(indicator);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 高亮技能范围
        function highlightAbilityRange(character, ability) {
            const container = document.getElementById('ability-indicators-container');
            const mapContainer = document.getElementById('game-map');
            const mapRect = mapContainer.getBoundingClientRect();
            const cellSize = 56; // 格子大小(px)

            // 设置容器位置
            container.style.left = `${mapRect.left}px`;
            container.style.top = `${mapRect.top}px`;
            container.style.width = `${mapRect.width}px`;
            container.style.height = `${mapRect.height}px`;

            // 创建范围指示器
            const rangeIndicator = document.createElement('div');
            rangeIndicator.classList.add('ability-range-indicator');

            // 根据技能范围设置大小和位置
            const range = ability.range;
            rangeIndicator.style.width = `${(range * 2 + 1) * cellSize}px`;
            rangeIndicator.style.height = `${(range * 2 + 1) * cellSize}px`;
            rangeIndicator.style.left = `${(character.x - range) * cellSize}px`;
            rangeIndicator.style.top = `${(character.y - range) * cellSize}px`;

            container.appendChild(rangeIndicator);

            // 高亮有效目标
            for (let dy = -range; dy <= range; dy++) {
                for (let dx = -range; dx <= range; dx++) {
                    // 计算曼哈顿距离
                    const distance = Math.abs(dx) + Math.abs(dy);
                    if (distance > range) continue;

                    const x = character.x + dx;
                    const y = character.y + dy;

                    // 检查是否在地图范围内
                    if (x >= 0 && x < GAME_CONFIG.mapSize && y >= 0 && y < GAME_CONFIG.mapSize) {
                        // 检查是否是障碍物
                        if (gameState.map[y][x].type !== CELL_TYPES.OBSTACLE) {
                            // 检查目标是否符合技能要求
                            const target = getCharacterAtPosition(x, y);
                            let isValidTarget = false;

                            if (ability.target === 'enemy' && target && target.type === CHARACTER_TYPES.ENEMY) {
                                isValidTarget = true;
                            } else if (ability.target === 'ally' && target && target.type === CHARACTER_TYPES.PLAYER) {
                                isValidTarget = true;
                            } else if (ability.target === 'self' && x === character.x && y === character.y) {
                                isValidTarget = true;
                            } else if (ability.target === 'any') {
                                isValidTarget = true;
                            }

                            if (isValidTarget) {
                                const cell = document.querySelector(`.grid-cell[data-x="${x}"][data-y="${y}"]`);
                                if (cell) {
                                    cell.classList.add('grid-cell-ability');

                                    // 添加技能提示
                                    if (!cell.querySelector('.ability-indicator')) {
                                        const indicator = document.createElement('div');
                                        indicator.classList.add('ability-indicator', 'text-xs', 'text-purple-600', 'opacity-70', 'absolute');
                                        indicator.textContent = ability.name;
                                        cell.appendChild(indicator);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 清除技能范围指示器
        function clearAbilityIndicators() {
            const container = document.getElementById('ability-indicators-container');
            container.innerHTML = '';
        }

        // 处理移动
        function handleMove() {
            // 取消任何激活的技能
            if (gameState.activeAbility) {
                gameState.activeAbility = null;
                renderMap();
            }

            if (!gameState.selectedCharacter) {
                showInfo('请先选择一个角色');
                return;
            }

            // 如果角色已经移动过，不能再操作
            if (gameState.selectedCharacter.moved) {
                showInfo(`${gameState.selectedCharacter.fullName}已经移动过了`);
                return;
            }

            // 如果已经选择了目标格子，直接移动
            if (gameState.selectedCell) {
                const { x, y } = gameState.selectedCell;
                const character = gameState.selectedCharacter;

                // 检查目标位置是否有敌人
                const targetChar = getCharacterAtPosition(x, y);
                if (targetChar && targetChar.type === CHARACTER_TYPES.ENEMY) {
                    showInfo('目标位置有敌人，不能移动过去，请选择攻击');
                    return;
                }

                // 检查是否是障碍物
                if (gameState.map[y][x].type === CELL_TYPES.OBSTACLE) {
                    showInfo('目标位置是障碍物，不能移动过去');
                    return;
                }

                // 检查是否在移动范围内（简单距离检查）
                const distance = Math.max(Math.abs(x - character.x), Math.abs(y - character.y));
                if (distance > 2) {
                    showInfo('距离太远，不能移动过去');
                    return;
                }

                // 显示移动确认
                showMoveConfirmation(x, y);
            } else {
                showInfo('请先选择一个目标位置');
            }
        }

        // 处理攻击
        function handleAttack() {
            // 取消任何激活的技能
            if (gameState.activeAbility) {
                gameState.activeAbility = null;
                renderMap();
            }

            if (!gameState.selectedCharacter) {
                showInfo('请先选择一个角色');
                return;
            }

            // 如果角色已经移动过，不能再操作
            if (gameState.selectedCharacter.moved) {
                showInfo(`${gameState.selectedCharacter.fullName}已经行动过了`);
                return;
            }

            // 如果已经选择了目标格子，直接攻击
            if (gameState.selectedCell) {
                const { x, y } = gameState.selectedCell;
                const attacker = gameState.selectedCharacter;
                const defender = getCharacterAtPosition(x, y);

                // 检查目标是否是敌人
                if (!defender || defender.type !== CHARACTER_TYPES.ENEMY) {
                    showInfo('目标位置没有敌人');
                    return;
                }

                // 检查距离是否可以攻击（相邻格子）
                const distance = Math.max(Math.abs(x - attacker.x), Math.abs(y - attacker.y));
                if (distance > 1) {
                    showInfo('距离太远，不能攻击');
                    return;
                }

                // 执行攻击
                performAttack(attacker, defender, x, y);
            } else {
                showInfo('请先选择一个敌人');
            }
        }

        // 执行攻击操作
        function performAttack(attacker, defender, x, y) {
            // 播放攻击音效
            SoundManager.play('attack');

            // 计算伤害，考虑防御和临时加成
            const attackValue = attacker.attack + (attacker.temporaryAttack || 0);
            const defenseValue = defender.defense + (defender.temporaryDefense || 0);
            let damage = Math.max(1, attackValue - Math.floor(defenseValue / 3) - Math.floor(Math.random() * 3));

            // 检查是否有技能影响
            if (defender.fullName === '典韦' && defender.abilities[1] && defender.abilities[1].name === '狂怒') {
                const hpPercent = defender.hp / defender.maxHp;
                const rageBonus = Math.max(0, Math.floor((1 - hpPercent) * 10));
                damage = Math.max(1, damage - rageBonus);
                logMessage(`${defender.fullName}因狂怒减少了${rageBonus}点伤害！`);
            }

            defender.hp -= damage;

            // 显示伤害数字
            showDamageIndicator(x, y, damage);

            // 添加受伤动画
            const defenderElement = document.querySelector(`.character[data-id="${defender.id}"]`);
            if (defenderElement) {
                defenderElement.classList.add('character-hurt');
            }

            logMessage(`${attacker.fullName}攻击了${defender.fullName}，造成${damage}点伤害!`);

            // 曹操的奸雄技能：攻击后恢复自身造成伤害的30%
            if (attacker.fullName === '曹操' && attacker.abilities[0] && attacker.abilities[0].name === '奸雄' &&
                attacker.abilities[0].currentCooldown === 0) {
                const healAmount = Math.floor(damage * 0.3);
                attacker.hp = Math.min(attacker.maxHp, attacker.hp + healAmount);
                showHealIndicator(attacker.x, attacker.y, healAmount);
                logMessage(`${attacker.fullName}触发了奸雄技能，恢复了${healAmount}点生命值！`);
                SoundManager.play('heal');

                // 触发冷却
                attacker.abilities[0].currentCooldown = attacker.abilities[0].cooldown;
            }

            // 夏侯惇的刚烈技能：受到攻击时反弹20%伤害
            if (defender.fullName === '夏侯惇' && defender.abilities[0] && defender.abilities[0].name === '刚烈' &&
                defender.abilities[0].currentCooldown === 0 && defender.hp > 0) {
                const reflectDamage = Math.floor(damage * 0.2);
                attacker.hp = Math.max(1, attacker.hp - reflectDamage);
                showDamageIndicator(attacker.x, attacker.y, reflectDamage);
                logMessage(`${defender.fullName}触发了刚烈技能，反弹了${reflectDamage}点伤害！`);
                SoundManager.play('hit');

                // 触发冷却
                defender.abilities[0].currentCooldown = defender.abilities[0].cooldown;
            }

            // 播放被击中音效
            SoundManager.play('hit');

            // 检查敌人是否被击败
            if (defender.hp <= 0) {
                // 添加死亡动画
                if (defenderElement) {
                    defenderElement.classList.add('character-dying');
                }

                logMessage(`${defender.fullName}被击败了!`);

                // 玩家获得经验值
                const expGained = 50 + (defender.isElite ? 30 : 0) + Math.floor(gameState.level * 10);
                attacker.experience += expGained;
                logMessage(`${attacker.fullName}获得了${expGained}点经验值！`);

                // 检查是否升级
                checkLevelUp(attacker);

                // 从角色列表中移除
                setTimeout(() => {
                    gameState.characters = gameState.characters.filter(char => char.id !== defender.id);

                    // 更新关卡进度
                    updateLevelProgress();

                    // 检查是否所有敌人都被击败
                    checkVictory();

                    renderMap();
                }, 1000);
            }

            attacker.moved = true; // 攻击后不能再移动

            // 更新技能冷却
            updateAbilityCooldowns();

            // 动画结束后重新渲染地图
            if (defender.hp > 0) {
                setTimeout(() => {
                    renderMap();
                }, 500);
            }
        }

        // 处理技能
        function handleAbility() {
            if (!gameState.selectedCharacter || gameState.selectedCharacter.type !== CHARACTER_TYPES.PLAYER) {
                showInfo('请先选择一个己方武将');
                return;
            }

            const character = gameState.selectedCharacter;

            // 如果角色已经移动过，不能再操作
            if (character.moved) {
                showInfo(`${character.fullName}已经行动过了`);
                return;
            }

            // 检查是否有可用技能
            const availableAbilities = character.abilities.filter(ability => ability.currentCooldown === 0);

            if (availableAbilities.length === 0) {
                showInfo(`${character.fullName}没有可用技能（技能正在冷却中）`);
                return;
            }

            // 如果已经有激活的技能，则取消
            if (gameState.activeAbility) {
                gameState.activeAbility = null;
                renderMap();
                showInfo(`${character.fullName}的技能已取消`);
                return;
            }

            // 显示技能选择弹窗
            showEventPopup(
                `${character.fullName}的技能`,
                '选择要使用的技能:',
                availableAbilities.map(ability => ({
                    text: `${ability.name} - ${ability.description} (范围: ${ability.range})`,
                    action: () => {
                        gameState.activeAbility = ability;
                        hideEventPopup();
                        renderMap(); // 重新渲染以显示技能范围
                        showInfo(`已选择${ability.name}，请选择目标`);
                    }
                }))
            );
        }

        // 使用选中的技能
        function useSelectedAbility() {
            if (!gameState.activeAbility || !gameState.selectedCharacter || !gameState.selectedCell) {
                return;
            }

            const ability = gameState.activeAbility;
            const character = gameState.selectedCharacter;
            const { x, y } = gameState.selectedCell;

            // 播放技能音效
            SoundManager.play('ability');

            // 根据不同技能执行不同效果
            switch (character.fullName) {
                case '刘备':
                    if (ability.name === '仁德') {
                        // 恢复周围友军10点生命值
                        let healed = false;
                        for (let dy = -ability.range; dy <= ability.range; dy++) {
                            for (let dx = -ability.range; dx <= ability.range; dx++) {
                                const nx = character.x + dx;
                                const ny = character.y + dy;

                                const ally = getCharacterAtPosition(nx, ny);
                                if (ally && ally.type === CHARACTER_TYPES.PLAYER) {
                                    const healAmount = 10 + Math.floor(character.level / 2);
                                    ally.hp = Math.min(ally.maxHp, ally.hp + healAmount);
                                    showHealIndicator(nx, ny, healAmount);
                                    healed = true;
                                }
                            }
                        }

                        if (healed) {
                            logMessage(`${character.fullName}使用了仁德技能，恢复了友军的生命值！`);
                        } else {
                            logMessage(`${character.fullName}使用了仁德技能，但周围没有友军！`);
                        }
                    } else if (ability.name === '义勇') {
                        // 提升自身和相邻友军的防御力2回合
                        for (let dy = -ability.range; dy <= ability.range; dy++) {
                            for (let dx = -ability.range; dx <= ability.range; dx++) {
                                const nx = character.x + dx;
                                const ny = character.y + dy;

                                const ally = getCharacterAtPosition(nx, ny);
                                if (ally && ally.type === CHARACTER_TYPES.PLAYER) {
                                    // 检查是否已有该状态
                                    const existingEffect = ally.statusEffects.find(e => e.type === 'defense_up');
                                    if (existingEffect) {
                                        existingEffect.duration = 2; // 刷新持续时间
                                    } else {
                                        ally.statusEffects.push({
                                            type: 'defense_up',
                                            duration: 2
                                        });
                                    }

                                    // 临时提升防御
                                    ally.temporaryDefense = (ally.temporaryDefense || 0) + 3;
                                    ally.temporaryDefenseDuration = 2;
                                }
                            }
                        }
                        logMessage(`${character.fullName}使用了义勇技能，提升了友军的防御力！`);
                    }
                    break;

                case '关羽':
                    if (ability.name === '青龙斩') {
                        // 对单个敌人造成150%伤害
                        const defender = getCharacterAtPosition(x, y);
                        if (defender && defender.type === CHARACTER_TYPES.ENEMY) {
                            const attackValue = character.attack + (character.temporaryAttack || 0);
                            const defenseValue = defender.defense + (defender.temporaryDefense || 0);
                            const damage = Math.floor(attackValue * 1.5 - Math.floor(defenseValue / 3));
                            defender.hp -= damage;
                            showDamageIndicator(x, y, damage);

                            logMessage(`${character.fullName}使用了青龙斩，对${defender.fullName}造成了${damage}点伤害！`);

                            // 受伤动画
                            const defenderElement = document.querySelector(`.character[data-id="${defender.id}"]`);
                            if (defenderElement) {
                                defenderElement.classList.add('character-hurt');
                            }

                            // 检查敌人是否被击败
                            if (defender.hp <= 0) {
                                if (defenderElement) {
                                    defenderElement.classList.add('character-dying');
                                }

                                logMessage(`${defender.fullName}被击败了!`);

                                // 玩家获得经验值
                                const expGained = 50 + (defender.isElite ? 30 : 0) + Math.floor(gameState.level * 10);
                                character.experience += expGained;
                                logMessage(`${character.fullName}获得了${expGained}点经验值！`);

                                // 检查是否升级
                                checkLevelUp(character);

                                // 延迟移除死亡单位
                                setTimeout(() => {
                                    gameState.characters = gameState.characters.filter(char => char.id !== defender.id);
                                    updateLevelProgress();
                                    checkVictory();
                                    renderMap();
                                }, 1000);
                            }
                        }
                    } else if (ability.name === '忠义') {
                        // 保护相邻的友军，承受他们受到的伤害
                        character.statusEffects.push({
                            type: 'protect',
                            duration: 2
                        });
                        logMessage(`${character.fullName}使用了忠义技能，开始保护相邻友军！`);
                    }
                    break;

                case '张飞':
                    if (ability.name === '咆哮') {
                        // 对周围所有敌人造成少量伤害并震慑他们
                        let enemiesHit = 0;
                        for (let dy = -ability.range; dy <= ability.range; dy++) {
                            for (let dx = -ability.range; dx <= ability.range; dx++) {
                                if (dx === 0 && dy === 0) continue; // 跳过自己

                                const nx = character.x + dx;
                                const ny = character.y + dy;

                                const enemy = getCharacterAtPosition(nx, ny);
                                if (enemy && enemy.type === CHARACTER_TYPES.ENEMY) {
                                    const attackValue = character.attack + (character.temporaryAttack || 0);
                                    const defenseValue = enemy.defense + (enemy.temporaryDefense || 0);
                                    const damage = Math.max(1, Math.floor(attackValue * 0.7 - Math.floor(defenseValue / 3)));
                                    enemy.hp -= damage;

                                    // 添加震慑效果
                                    enemy.statusEffects.push({
                                        type: 'stunned',
                                        duration: 1
                                    });

                                    showDamageIndicator(nx, ny, damage);
                                    enemiesHit++;

                                    // 受伤动画
                                    const enemyElement = document.querySelector(`.character[data-id="${enemy.id}"]`);
                                    if (enemyElement) {
                                        enemyElement.classList.add('character-hurt');
                                    }
                                }
                            }
                        }

                        if (enemiesHit > 0) {
                            logMessage(`${character.fullName}使用了咆哮，对${enemiesHit}个敌人造成了伤害并震慑了他们！`);
                        } else {
                            logMessage(`${character.fullName}使用了咆哮，但周围没有敌人！`);
                        }
                    } else if (ability.name === '破胆') {
                        // 使单个敌人下一回合无法行动
                        const defender = getCharacterAtPosition(x, y);
                        if (defender && defender.type === CHARACTER_TYPES.ENEMY) {
                            // 添加震慑效果
                            defender.statusEffects.push({
                                type: 'stunned',
                                duration: 1
                            });

                            logMessage(`${character.fullName}使用了破胆，${defender.fullName}被震慑了！`);

                            // 显示效果指示
                            const effectIndicator = document.createElement('div');
                            effectIndicator.classList.add('damage-indicator');
                            effectIndicator.innerHTML = '<i class="fa fa-ban text-yellow-500"></i>';

                            // 计算位置
                            const cellSize = 56; // 格子大小(px)
                            effectIndicator.style.left = `${x * cellSize + cellSize / 2}px`;
                            effectIndicator.style.top = `${y * cellSize}px`;

                            document.getElementById('game-map').appendChild(effectIndicator);

                            // 动画结束后移除元素
                            setTimeout(() => {
                                effectIndicator.remove();
                            }, 1000);
                        }
                    }
                    break;
            }

            // 设置技能冷却
            ability.currentCooldown = ability.cooldown;

            // 使用技能后不能再行动
            character.moved = true;

            // 清除激活的技能
            gameState.activeAbility = null;

            // 重新渲染
            setTimeout(() => {
                renderMap();
            }, 500);
        }

        // 显示伤害数字
        function showDamageIndicator(x, y, value) {
            const mapContainer = document.getElementById('game-map');
            const indicator = document.createElement('div');
            indicator.classList.add('damage-indicator');
            indicator.textContent = value;

            // 计算位置
            const cellSize = 56; // 格子大小(px)
            indicator.style.left = `${x * cellSize + cellSize / 2}px`;
            indicator.style.top = `${y * cellSize}px`;

            mapContainer.appendChild(indicator);

            // 动画结束后移除元素
            setTimeout(() => {
                indicator.remove();
            }, 1000);
        }

        // 显示治疗数字
        function showHealIndicator(x, y, value) {
            const mapContainer = document.getElementById('game-map');
            const indicator = document.createElement('div');
            indicator.classList.add('heal-indicator');
            indicator.textContent = `+${value}`;

            // 计算位置
            const cellSize = 56; // 格子大小(px)
            indicator.style.left = `${x * cellSize + cellSize / 2}px`;
            indicator.style.top = `${y * cellSize}px`;

            mapContainer.appendChild(indicator);

            // 动画结束后移除元素
            setTimeout(() => {
                indicator.remove();
            }, 1000);
        }

        // 收集物品
        function collectItem(character, cell) {
            SoundManager.play('item');

            switch (cell.itemType) {
                case ITEM_TYPES.POTION:
                    const healAmount = 30 + Math.floor(Math.random() * 20) + Math.floor(character.level * 5);
                    character.hp = Math.min(character.maxHp, character.hp + healAmount);
                    logMessage(`${character.fullName}找到了治疗药剂，恢复了${healAmount}点生命值!`);

                    // 显示治疗数字
                    showHealIndicator(character.x, character.y, healAmount);

                    showNotification(`${character.fullName}恢复了${healAmount}点生命值!`);
                    break;

                case ITEM_TYPES.WEAPON:
                    const attackBoost = 5 + Math.floor(Math.random() * 5) + Math.floor(character.level * 2);
                    character.attack += attackBoost;
                    logMessage(`${character.fullName}找到了精良武器，攻击力提升了${attackBoost}点!`);

                    showNotification(`${character.fullName}攻击力提升${attackBoost}点!`);
                    break;

                case ITEM_TYPES.ARMOR:
                    const defenseBoost = 3 + Math.floor(Math.random() * 3) + Math.floor(character.level * 1);
                    character.defense += defenseBoost;
                    logMessage(`${character.fullName}找到了坚固防具，防御力提升了${defenseBoost}点!`);

                    showNotification(`${character.fullName}防御力提升${defenseBoost}点!`);
                    break;

                case ITEM_TYPES.TREASURE:
                    const expBoost = 50 + Math.floor(Math.random() * 50) + Math.floor(character.level * 10);
                    character.experience += expBoost;
                    logMessage(`${character.fullName}找到了宝藏，获得了${expBoost}点经验值!`);

                    // 检查是否升级
                    checkLevelUp(character);

                    showNotification(`${character.fullName}获得了${expBoost}点经验值!`);
                    break;

                case ITEM_TYPES.SCROLL:
                    // 随机效果：重置技能冷却或提升属性
                    if (Math.random() < 0.5) {
                        // 重置技能冷却
                        character.abilities.forEach(ability => {
                            ability.currentCooldown = 0;
                        });
                        logMessage(`${character.fullName}使用了魔法卷轴，所有技能冷却已重置!`);
                        showNotification(`${character.fullName}的技能冷却已重置!`);
                    } else {
                        // 提升属性
                        const boostType = Math.random() < 0.5 ? 'attack' : 'defense';
                        const boostAmount = 3 + Math.floor(Math.random() * 3);
                        character[boostType] += boostAmount;
                        logMessage(`${character.fullName}使用了魔法卷轴，${boostType === 'attack' ? '攻击力' : '防御力'}提升了${boostAmount}点!`);
                        showNotification(`${character.fullName}${boostType === 'attack' ? '攻击力' : '防御力'}提升${boostAmount}点!`);
                    }
                    break;
            }
        }

        // 触发事件
        function triggerEvent(x, y) {
            const cell = gameState.map[y][x];
            if (cell.type !== CELL_TYPES.EVENT) return;

            // 播放事件音效
            SoundManager.play('event');

            // 标记事件已处理
            cell.type = CELL_TYPES.EMPTY;

            switch (cell.eventType) {
                case EVENT_TYPES.MERCHANT:
                    // 商人事件：可以购买物品
                    const itemsForSale = [
                        { name: '治疗药剂', price: 50, type: ITEM_TYPES.POTION },
                        { name: '强效治疗药剂', price: 100, type: ITEM_TYPES.POTION, effect: 80 },
                        { name: '攻击卷轴', price: 70, type: ITEM_TYPES.SCROLL, effect: 'attack' },
                        { name: '防御卷轴', price: 70, type: ITEM_TYPES.SCROLL, effect: 'defense' },
                        { name: '技能重置卷轴', price: 120, type: ITEM_TYPES.SCROLL, effect: 'reset' }
                    ];

                    // 随机选择3件商品
                    const availableItems = [];
                    while (availableItems.length < 3) {
                        const randomItem = itemsForSale[Math.floor(Math.random() * itemsForSale.length)];
                        if (!availableItems.some(item => item.name === randomItem.name)) {
                            availableItems.push(randomItem);
                        }
                    }

                    // 创建购买选项
                    const choices = availableItems.map(item => ({
                        text: `${item.name} - 价格: ${item.price}金币`,
                        action: () => {
                            // 简单处理：假设玩家有足够金币购买
                            logMessage(`${gameState.selectedCharacter.fullName}购买了${item.name}`);

                            // 应用物品效果
                            if (item.type === ITEM_TYPES.POTION) {
                                const healAmount = item.effect || 50;
                                gameState.selectedCharacter.hp = Math.min(
                                    gameState.selectedCharacter.maxHp,
                                    gameState.selectedCharacter.hp + healAmount
                                );
                                showHealIndicator(
                                    gameState.selectedCharacter.x,
                                    gameState.selectedCharacter.y,
                                    healAmount
                                );
                                showNotification(`购买了${item.name}，恢复了${healAmount}点生命值!`);
                            } else if (item.type === ITEM_TYPES.SCROLL) {
                                if (item.effect === 'attack') {
                                    const boost = 5;
                                    gameState.selectedCharacter.attack += boost;
                                    showNotification(`购买了${item.name}，攻击力提升${boost}点!`);
                                } else if (item.effect === 'defense') {
                                    const boost = 5;
                                    gameState.selectedCharacter.defense += boost;
                                    showNotification(`购买了${item.name}，防御力提升${boost}点!`);
                                } else if (item.effect === 'reset') {
                                    gameState.selectedCharacter.abilities.forEach(ability => {
                                        ability.currentCooldown = 0;
                                    });
                                    showNotification(`购买了${item.name}，技能冷却已重置!`);
                                }
                            }

                            hideEventPopup();
                        }
                    }));

                    // 添加不购买选项
                    choices.push({
                        text: '不购买任何物品',
                        action: () => {
                            logMessage(`${gameState.selectedCharacter.fullName}离开了商人`);
                            hideEventPopup();
                        }
                    });

                    showEventPopup(
                        '遇到了商人',
                        '商人正在出售一些物品，你想要购买什么?',
                        choices
                    );
                    break;

                case EVENT_TYPES.SHRINE:
                    // 神社事件：随机获得祝福或诅咒
                    if (Math.random() < 0.7) {
                        // 祝福
                        const blessings = [
                            { type: 'heal', text: '获得了治愈祝福，恢复全部生命值' },
                            { type: 'attack', text: '获得了力量祝福，攻击力永久+5' },
                            { type: 'defense', text: '获得了守护祝福，防御力永久+5' },
                            { type: 'exp', text: '获得了智慧祝福，经验值+100' },
                            { type: 'regeneration', text: '获得了再生祝福，每回合恢复生命值' }
                        ];

                        const blessing = blessings[Math.floor(Math.random() * blessings.length)];
                        const character = gameState.selectedCharacter;

                        switch (blessing.type) {
                            case 'heal':
                                const healAmount = character.maxHp - character.hp;
                                character.hp = character.maxHp;
                                showHealIndicator(character.x, character.y, healAmount);
                                break;
                            case 'attack':
                                character.attack += 5;
                                break;
                            case 'defense':
                                character.defense += 5;
                                break;
                            case 'exp':
                                character.experience += 100;
                                checkLevelUp(character);
                                break;
                            case 'regeneration':
                                character.statusEffects.push({
                                    type: 'regeneration',
                                    duration: -1 // 永久效果，直到战斗结束
                                });
                                break;
                        }

                        logMessage(`${character.fullName}${blessing.text}`);
                        showEventPopup(
                            '神社的祝福',
                            `${character.fullName}${blessing.text}`,
                            [{ text: '感谢神明', action: hideEventPopup }]
                        );
                    } else {
                        // 诅咒
                        const curses = [
                            { type: 'damage', text: '受到了诅咒，损失30点生命值' },
                            { type: 'attack', text: '受到了虚弱诅咒，攻击力-3' },
                            { type: 'defense', text: '受到了脆弱诅咒，防御力-3' },
                            { type: 'stun', text: '受到了麻痹诅咒，本回合无法行动' }
                        ];

                        const curse = curses[Math.floor(Math.random() * curses.length)];
                        const character = gameState.selectedCharacter;

                        switch (curse.type) {
                            case 'damage':
                                const damage = 30;
                                character.hp = Math.max(1, character.hp - damage);
                                showDamageIndicator(character.x, character.y, damage);
                                break;
                            case 'attack':
                                character.attack = Math.max(1, character.attack - 3);
                                break;
                            case 'defense':
                                character.defense = Math.max(1, character.defense - 3);
                                break;
                            case 'stun':
                                character.moved = true; // 强制结束行动
                                character.statusEffects.push({
                                    type: 'stunned',
                                    duration: 1
                                });
                                break;
                        }

                        logMessage(`${character.fullName}${curse.text}`);
                        showEventPopup(
                            '邪恶的诅咒',
                            `${character.fullName}${curse.text}`,
                            [{ text: '真倒霉', action: hideEventPopup }]
                        );
                    }
                    break;

                case EVENT_TYPES.TREASURE_ROOM:
                    // 宝藏室事件：获得多种奖励
                    const rewards = [
                        { type: 'gold', value: 100 + Math.floor(Math.random() * 100) },
                        { type: 'item', item: Object.values(ITEM_TYPES)[Math.floor(Math.random() * Object.values(ITEM_TYPES).length)] },
                        { type: 'exp', value: 100 + Math.floor(Math.random() * 100) }
                    ];

                    let rewardText = '';
                    const character = gameState.selectedCharacter;

                    rewards.forEach(reward => {
                        if (reward.type === 'gold') {
                            rewardText += `<br>获得了${reward.value}金币`;
                        } else if (reward.type === 'exp') {
                            character.experience += reward.value;
                            checkLevelUp(character);
                            rewardText += `<br>获得了${reward.value}经验值`;
                        } else if (reward.type === 'item') {
                            // 应用物品效果
                            let itemName = '';
                            switch (reward.item) {
                                case ITEM_TYPES.POTION:
                                    itemName = '治疗药剂';
                                    const healAmount = 50;
                                    character.hp = Math.min(character.maxHp, character.hp + healAmount);
                                    showHealIndicator(character.x, character.y, healAmount);
                                    rewardText += `<br>获得了${itemName}，恢复了${healAmount}点生命值`;
                                    break;
                                case ITEM_TYPES.WEAPON:
                                    itemName = '精良武器';
                                    const attackBoost = 7;
                                    character.attack += attackBoost;
                                    rewardText += `<br>获得了${itemName}，攻击力提升${attackBoost}点`;
                                    break;
                                case ITEM_TYPES.ARMOR:
                                    itemName = '坚固防具';
                                    const defenseBoost = 5;
                                    character.defense += defenseBoost;
                                    rewardText += `<br>获得了${itemName}，防御力提升${defenseBoost}点`;
                                    break;
                                case ITEM_TYPES.TREASURE:
                                    itemName = '珍贵宝藏';
                                    const expBoost = 100;
                                    character.experience += expBoost;
                                    checkLevelUp(character);
                                    rewardText += `<br>获得了${itemName}，获得了${expBoost}点经验值`;
                                    break;
                                case ITEM_TYPES.SCROLL:
                                    itemName = '神秘卷轴';
                                    character.abilities.forEach(ability => {
                                        ability.currentCooldown = 0;
                                    });
                                    rewardText += `<br>获得了${itemName}，技能冷却已重置`;
                                    break;
                            }
                        }
                    });

                    logMessage(`${character.fullName}发现了宝藏室！${rewardText.replace(/<br>/g, ' ')}`);
                    showEventPopup(
                        '发现宝藏室',
                        `${character.fullName}发现了宝藏室！${rewardText}`,
                        [{ text: '带走宝藏', action: hideEventPopup }]
                    );
                    break;

                case EVENT_TYPES.AMBUSH:
                    // 埋伏事件：突然遭遇敌人
                    const ambushCount = 1 + Math.floor(Math.random() * 2);
                    let ambushText = `${gameState.selectedCharacter.fullName}遭遇了${ambushCount}个埋伏的敌人！`;

                    logMessage(ambushText);

                    // 创建埋伏的敌人
                    setTimeout(() => {
                        for (let i = 0; i < ambushCount; i++) {
                            // 寻找附近的空位
                            let nx, ny;
                            let foundPosition = false;

                            for (let dy = -2; dy <= 2 && !foundPosition; dy++) {
                                for (let dx = -2; dx <= 2 && !foundPosition; dx++) {
                                    if (dx === 0 && dy === 0) continue; // 跳过玩家位置

                                    nx = gameState.selectedCharacter.x + dx;
                                    ny = gameState.selectedCharacter.y + dy;

                                    // 检查是否在地图范围内且为空位
                                    if (nx >= 0 && nx < GAME_CONFIG.mapSize && ny >= 0 && ny < GAME_CONFIG.mapSize) {
                                        if (gameState.map[ny][nx].type !== CELL_TYPES.OBSTACLE &&
                                            !getCharacterAtPosition(nx, ny)) {
                                            foundPosition = true;
                                        }
                                    }
                                }
                            }

                            if (!foundPosition) {
                                // 如果没找到位置，就放在玩家旁边
                                nx = gameState.selectedCharacter.x + 1;
                                ny = gameState.selectedCharacter.y;
                                if (nx >= GAME_CONFIG.mapSize) {
                                    nx = gameState.selectedCharacter.x - 1;
                                }
                            }

                            // 创建敌人
                            const enemyTypes = [
                                { names: ['曹兵', '曹兵'], color: 'bg-red-500', hp: 50, attack: 8, defense: 3 },
                                { names: ['夏侯部', '夏侯部将'], color: 'bg-orange-500', hp: 70, attack: 10, defense: 4 }
                            ];

                            const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];

                            gameState.characters.push({
                                id: `ambush-enemy-${Date.now()}-${i}`,
                                type: CHARACTER_TYPES.ENEMY,
                                name: enemyType.names[0],
                                fullName: enemyType.names[1],
                                color: enemyType.color,
                                x: nx,
                                y: ny,
                                hp: enemyType.hp,
                                maxHp: enemyType.hp,
                                attack: enemyType.attack,
                                defense: enemyType.defense,
                                abilities: [],
                                statusEffects: []
                            });
                        }

                        // 强制结束当前角色的行动
                        if (gameState.selectedCharacter) {
                            gameState.selectedCharacter.moved = true;
                        }

                        renderMap();
                        updateEnemyCount();
                        hideEventPopup();
                    }, 1000);

                    showEventPopup(
                        '遭遇埋伏！',
                        ambushText,
                        [{ text: '准备战斗', action: () => { } }] // 空操作，等待敌人生成
                    );
                    break;

                case EVENT_TYPES.TRAINER:
                    // 训练师事件：提升属性
                    const stats = [
                        { name: '生命值', stat: 'hp', boost: 30 },
                        { name: '攻击力', stat: 'attack', boost: 5 },
                        { name: '防御力', stat: 'defense', boost: 5 },
                        { name: '技能冷却', stat: 'cooldown', boost: -1 }
                    ];

                    // 随机选择3个属性供选择
                    const availableStats = [];
                    while (availableStats.length < 3) {
                        const randomStat = stats[Math.floor(Math.random() * stats.length)];
                        if (!availableStats.some(s => s.stat === randomStat.stat)) {
                            availableStats.push(randomStat);
                        }
                    }

                    // 创建选择
                    const statChoices = availableStats.map(stat => ({
                        text: `提升${stat.name}${stat.boost > 0 ? '+' : ''}${stat.boost}`,
                        action: () => {
                            const character = gameState.selectedCharacter;

                            if (stat.stat === 'hp') {
                                character.maxHp += stat.boost;
                                character.hp = character.maxHp; // 同时恢复满生命值
                                showHealIndicator(character.x, character.y, stat.boost);
                                logMessage(`${character.fullName}提升了${stat.boost}点生命值上限`);
                            } else if (stat.stat === 'attack') {
                                character.attack += stat.boost;
                                logMessage(`${character.fullName}提升了${stat.boost}点攻击力`);
                            } else if (stat.stat === 'defense') {
                                character.defense += stat.boost;
                                logMessage(`${character.fullName}提升了${stat.boost}点防御力`);
                            } else if (stat.stat === 'cooldown') {
                                character.abilities.forEach(ability => {
                                    ability.cooldown = Math.max(1, ability.cooldown + stat.boost);
                                });
                                logMessage(`${character.fullName}的技能冷却时间减少了1回合`);
                            }

                            showNotification(`${character.fullName}${stat.name}得到了提升！`);
                            hideEventPopup();
                        }
                    }));

                    showEventPopup(
                        '遇到训练师',
                        '训练师可以帮你提升一项能力，选择一项:',
                        statChoices
                    );
                    break;

                case EVENT_TYPES.MYSTERY:
                    // 神秘事件：随机效果
                    const mysteryEvents = [
                        {
                            text: '发现了隐藏的通道，直接进入下一关', action: () => {
                                // 直接进入下一关
                                logMessage(`${gameState.selectedCharacter.fullName}发现了隐藏通道，直接进入下一关！`);
                                hideEventPopup();
                                setTimeout(nextLevel, 1000);
                            }
                        },
                        {
                            text: '遇到了一位隐士，传授了你特殊技能', action: () => {
                                const character = gameState.selectedCharacter;
                                // 随机添加一个新技能
                                const newAbilities = [
                                    { name: '急救', description: '立即恢复20点生命值', cooldown: 5, range: 0, type: 'heal', target: 'self' },
                                    { name: '闪避', description: '本回合闪避所有攻击', cooldown: 6, range: 0, type: 'buff', target: 'self' },
                                    { name: '会心一击', description: '下次攻击造成双倍伤害', cooldown: 4, range: 0, type: 'buff', target: 'self' }
                                ];

                                const newAbility = newAbilities[Math.floor(Math.random() * newAbilities.length)];
                                character.abilities.push({ ...newAbility, currentCooldown: 0 });

                                logMessage(`${character.fullName}学会了新技能：${newAbility.name}`);
                                showNotification(`${character.fullName}学会了新技能：${newAbility.name}`);
                                hideEventPopup();
                            }
                        },
                        {
                            text: '被神秘力量传送到了随机位置', action: () => {
                                const character = gameState.selectedCharacter;
                                // 保存旧位置
                                const oldX = character.x;
                                const oldY = character.y;

                                // 寻找随机空位
                                let newX, newY;
                                let attempts = 0;

                                do {
                                    newX = Math.floor(Math.random() * GAME_CONFIG.mapSize);
                                    newY = Math.floor(Math.random() * GAME_CONFIG.mapSize);
                                    attempts++;
                                } while ((gameState.map[newY][newX].type === CELL_TYPES.OBSTACLE ||
                                    getCharacterAtPosition(newX, newY)) && attempts < 100);

                                // 执行传送
                                character.x = newX;
                                character.y = newY;

                                logMessage(`${character.fullName}被传送到了(${newX}, ${newY})`);
                                showNotification(`${character.fullName}被传送到了新位置！`);

                                renderMap();
                                hideEventPopup();
                            }
                        },
                        {
                            text: '发现了一个宝箱，但需要放弃当前回合才能打开', action: () => {
                                // 强制结束当前回合
                                const character = gameState.selectedCharacter;
                                character.moved = true;

                                // 给予奖励
                                const gold = 100 + Math.floor(Math.random() * 100);
                                logMessage(`${character.fullName}打开了宝箱，获得了${gold}金币，但放弃了当前回合`);
                                showNotification(`获得了${gold}金币，但放弃了当前回合`);

                                hideEventPopup();
                                // 检查是否所有角色都已行动
                                checkAllMoved();
                            }
                        }
                    ];

                    const mysteryEvent = mysteryEvents[Math.floor(Math.random() * mysteryEvents.length)];

                    showEventPopup(
                        '神秘事件',
                        mysteryEvent.text,
                        [{ text: '接受命运', action: mysteryEvent.action }]
                    );
                    break;
            }
        }

        // 显示事件弹窗
        function showEventPopup(title, description, choices) {
            document.getElementById('event-title').textContent = title;
            document.getElementById('event-description').innerHTML = description;

            const choicesContainer = document.getElementById('event-choices');
            choicesContainer.innerHTML = '';

            choices.forEach(choice => {
                const button = document.createElement('button');
                button.classList.add('btn-game', 'w-full', 'justify-start');
                button.innerHTML = `<i class="fa fa-arrow-right mr-2"></i>${choice.text}`;
                button.addEventListener('click', choice.action);
                choicesContainer.appendChild(button);
            });

            document.getElementById('event-overlay').classList.remove('hidden');
            document.getElementById('event-popup').classList.remove('hidden');
        }

        // 隐藏事件弹窗
        function hideEventPopup() {
            document.getElementById('event-overlay').classList.add('hidden');
            document.getElementById('event-popup').classList.add('hidden');
        }

        // 检查是否升级
        function checkLevelUp(character) {
            while (character.experience >= character.nextLevelExp) {
                // 升级
                character.level++;
                character.experience -= character.nextLevelExp;
                character.nextLevelExp = Math.floor(character.nextLevelExp * 1.5);

                // 属性提升
                const hpBoost = 20 + Math.floor(Math.random() * 10);
                const attackBoost = 2 + Math.floor(Math.random() * 2);
                const defenseBoost = 1 + Math.floor(Math.random() * 2);

                character.maxHp += hpBoost;
                character.hp = character.maxHp; // 升级恢复满生命值
                character.attack += attackBoost;
                character.defense += defenseBoost;

                // 播放升级音效
                SoundManager.play('levelup');

                logMessage(`${character.fullName}升级到了${character.level}级！生命值+${hpBoost}，攻击力+${attackBoost}，防御力+${defenseBoost}`);
                showNotification(`${character.fullName}升级到了${character.level}级！`);

                // 显示升级效果
                showHealIndicator(character.x, character.y, hpBoost);
            }
        }

        // 结束玩家回合
        function endPlayerTurn() {
            // 检查是否还有未行动的角色
            const unmovedPlayers = gameState.characters.filter(
                char => char.type === CHARACTER_TYPES.PLAYER && !char.moved
            );

            if (unmovedPlayers.length > 0) {
                showEventPopup(
                    '确认结束回合',
                    `还有${unmovedPlayers.length}名武将尚未行动，确定要结束回合吗？`,
                    [
                        {
                            text: '确认结束', action: () => {
                                hideEventPopup();
                                proceedToEnemyTurn();
                            }
                        },
                        { text: '继续行动', action: hideEventPopup }
                    ]
                );
                return;
            }

            proceedToEnemyTurn();
        }

        // 进入敌人回合
        function proceedToEnemyTurn() {
            // 播放回合音效
            SoundManager.play('turn');

            gameState.turn = 'enemy';
            document.getElementById('turn-indicator').textContent = '敌人回合';
            document.getElementById('turn-indicator').classList.remove('bg-primary');
            document.getElementById('turn-indicator').classList.add('bg-red-500');

            // 清除选择
            cancelSelection();

            // 应用状态效果（回合开始时）
            applyStatusEffects('start');

            // 敌人行动
            const enemies = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY);
            processEnemyTurn(enemies, 0);
        }

        // 处理敌人回合
        function processEnemyTurn(enemies, index) {
            if (index >= enemies.length) {
                // 所有敌人行动完毕，回合结束
                endEnemyTurn();
                return;
            }

            const enemy = enemies[index];

            // 检查是否被震慑
            const isStunned = enemy.statusEffects.some(effect => effect.type === 'stunned');
            if (isStunned) {
                logMessage(`${enemy.fullName}被震慑了，无法行动！`);

                // 移除震慑效果
                enemy.statusEffects = enemy.statusEffects.filter(effect => effect.type !== 'stunned');

                // 继续处理下一个敌人
                setTimeout(() => processEnemyTurn(enemies, index + 1), 500);
                return;
            }

            // 查找附近的玩家
            const players = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);
            const targetPlayer = findClosestPlayer(enemy, players);

            if (!targetPlayer) {
                // 没有玩家了（游戏应该已经结束）
                endEnemyTurn();
                return;
            }

            // 检查是否可以攻击
            const distance = Math.max(Math.abs(targetPlayer.x - enemy.x), Math.abs(targetPlayer.y - enemy.y));

            if (distance <= 1) {
                // 可以攻击，执行攻击
                setTimeout(() => {
                    performEnemyAttack(enemy, targetPlayer);
                    // 继续处理下一个敌人
                    setTimeout(() => processEnemyTurn(enemies, index + 1), 1000);
                }, 500);
            } else {
                // 移动靠近玩家
                moveEnemyTowardsPlayer(enemy, targetPlayer);
                // 继续处理下一个敌人
                setTimeout(() => processEnemyTurn(enemies, index + 1), 1000);
            }
        }

        // 敌人攻击玩家
        function performEnemyAttack(enemy, player) {
            // 播放攻击音效
            SoundManager.play('attack');

            // 计算伤害
            const attackValue = enemy.attack + (enemy.temporaryAttack || 0);
            const defenseValue = player.defense + (player.temporaryDefense || 0);
            let damage = Math.max(1, attackValue - Math.floor(defenseValue / 3) - Math.floor(Math.random() * 3));

            // 检查是否有保护效果
            const protector = findProtector(player);
            if (protector) {
                // 由保护者承受伤害
                protector.hp -= damage;
                showDamageIndicator(protector.x, protector.y, damage);

                // 受伤动画
                const protectorElement = document.querySelector(`.character[data-id="${protector.id}"]`);
                if (protectorElement) {
                    protectorElement.classList.add('character-hurt');
                }

                logMessage(`${enemy.fullName}攻击了${player.fullName}，但${protector.fullName}挺身而出承受了${damage}点伤害！`);

                // 检查保护者是否被击败
                if (protector.hp <= 0) {
                    if (protectorElement) {
                        protectorElement.classList.add('character-dying');
                    }

                    logMessage(`${protector.fullName}被击败了!`);

                    // 延迟移除死亡单位
                    setTimeout(() => {
                        gameState.characters = gameState.characters.filter(char => char.id !== protector.id);
                        renderMap();
                        checkDefeat(); // 检查是否所有玩家都被击败
                    }, 1000);
                }
            } else {
                // 直接攻击玩家
                player.hp -= damage;
                showDamageIndicator(player.x, player.y, damage);

                // 受伤动画
                const playerElement = document.querySelector(`.character[data-id="${player.id}"]`);
                if (playerElement) {
                    playerElement.classList.add('character-hurt');
                }

                logMessage(`${enemy.fullName}攻击了${player.fullName}，造成${damage}点伤害!`);

                // 检查玩家是否被击败
                if (player.hp <= 0) {
                    if (playerElement) {
                        playerElement.classList.add('character-dying');
                    }

                    logMessage(`${player.fullName}被击败了!`);

                    // 延迟移除死亡单位
                    setTimeout(() => {
                        gameState.characters = gameState.characters.filter(char => char.id !== player.id);
                        renderMap();
                        checkDefeat(); // 检查是否所有玩家都被击败
                    }, 1000);
                }
            }

            // 播放被击中音效
            SoundManager.play('hit');

            // 重新渲染
            renderMap();
        }

        // 查找保护者
        function findProtector(target) {
            return gameState.characters.find(char =>
                char.type === CHARACTER_TYPES.PLAYER &&
                char.statusEffects.some(effect => effect.type === 'protect') &&
                Math.max(Math.abs(target.x - char.x), Math.abs(target.y - char.y)) <= 1
            );
        }

        // 敌人移动到玩家附近
        function moveEnemyTowardsPlayer(enemy, player) {
            // 计算移动方向
            let dx = 0;
            let dy = 0;

            if (player.x > enemy.x) {
                dx = 1;
            } else if (player.x < enemy.x) {
                dx = -1;
            }

            if (player.y > enemy.y) {
                dy = 1;
            } else if (player.y < enemy.y) {
                dy = -1;
            }

            // 检查目标位置是否可以移动
            const newX = enemy.x + dx;
            const newY = enemy.y + dy;

            // 检查是否在地图范围内
            if (newX >= 0 && newX < GAME_CONFIG.mapSize && newY >= 0 && newY < GAME_CONFIG.mapSize) {
                // 检查是否是障碍物
                if (gameState.map[newY][newX].type !== CELL_TYPES.OBSTACLE) {
                    // 检查是否有其他角色
                    const targetChar = getCharacterAtPosition(newX, newY);
                    if (!targetChar) {
                        // 可以移动
                        enemy.x = newX;
                        enemy.y = newY;
                        logMessage(`${enemy.fullName}移动到了(${newX}, ${newY})`);

                        // 播放移动音效
                        SoundManager.play('move');

                        // 重新渲染
                        renderMap();
                        return;
                    }
                }
            }

            // 如果不能按原方向移动，尝试其他方向
            const directions = [
                { dx: 1, dy: 0 }, { dx: -1, dy: 0 },
                { dx: 0, dy: 1 }, { dx: 0, dy: -1 },
                { dx: 1, dy: 1 }, { dx: 1, dy: -1 },
                { dx: -1, dy: 1 }, { dx: -1, dy: -1 }
            ];

            for (const dir of directions) {
                const newX = enemy.x + dir.dx;
                const newY = enemy.y + dir.dy;

                if (newX >= 0 && newX < GAME_CONFIG.mapSize && newY >= 0 && newY < GAME_CONFIG.mapSize) {
                    if (gameState.map[newY][newX].type !== CELL_TYPES.OBSTACLE) {
                        const targetChar = getCharacterAtPosition(newX, newY);
                        if (!targetChar) {
                            enemy.x = newX;
                            enemy.y = newY;
                            logMessage(`${enemy.fullName}移动到了(${newX}, ${newY})`);

                            // 播放移动音效
                            SoundManager.play('move');

                            renderMap();
                            return;
                        }
                    }
                }
            }

            // 无法移动
            logMessage(`${enemy.fullName}无法移动`);
        }

        // 查找最近的玩家
        function findClosestPlayer(enemy, players) {
            if (players.length === 0) return null;

            let closestPlayer = players[0];
            let closestDistance = Math.max(
                Math.abs(closestPlayer.x - enemy.x),
                Math.abs(closestPlayer.y - enemy.y)
            );

            for (let i = 1; i < players.length; i++) {
                const distance = Math.max(
                    Math.abs(players[i].x - enemy.x),
                    Math.abs(players[i].y - enemy.y)
                );

                if (distance < closestDistance) {
                    closestPlayer = players[i];
                    closestDistance = distance;
                }
            }

            return closestPlayer;
        }

        // 结束敌人回合
        function endEnemyTurn() {
            // 应用状态效果（回合结束时）
            applyStatusEffects('end');

            // 重置所有角色的移动状态
            gameState.characters.forEach(char => {
                char.moved = false;
            });

            // 更新技能冷却
            updateAbilityCooldowns();

            // 切换回玩家回合
            gameState.turn = 'player';
            document.getElementById('turn-indicator').textContent = '玩家回合';
            document.getElementById('turn-indicator').classList.remove('bg-red-500');
            document.getElementById('turn-indicator').classList.add('bg-primary');

            // 播放回合音效
            SoundManager.play('turn');

            logMessage('敌人回合结束，轮到玩家行动');
            renderMap();
        }

        // 应用状态效果
        function applyStatusEffects(timing) {
            gameState.characters.forEach(char => {
                // 复制状态效果数组，避免在迭代中修改
                const effects = [...char.statusEffects];

                effects.forEach(effect => {
                    // 回合开始时的效果
                    if (timing === 'start') {
                        switch (effect.type) {
                            case 'regeneration':
                                // 再生效果：每回合恢复生命值
                                const healAmount = 5 + Math.floor(char.level / 2);
                                char.hp = Math.min(char.maxHp, char.hp + healAmount);
                                if (char.type === CHARACTER_TYPES.PLAYER) {
                                    showHealIndicator(char.x, char.y, healAmount);
                                    logMessage(`${char.fullName}因再生效果恢复了${healAmount}点生命值`);
                                }
                                break;
                        }
                    }

                    // 减少持续时间（-1表示永久效果）
                    if (effect.duration > 0) {
                        effect.duration--;

                        // 效果结束
                        if (effect.duration === 0) {
                            // 移除临时属性加成
                            if (effect.type === 'defense_up' && char.temporaryDefense) {
                                char.temporaryDefense = Math.max(0, char.temporaryDefense - 3);
                                if (char.type === CHARACTER_TYPES.PLAYER) {
                                    logMessage(`${char.fullName}的防御提升效果结束了`);
                                }
                            } else if (effect.type === 'attack_up' && char.temporaryAttack) {
                                char.temporaryAttack = Math.max(0, char.temporaryAttack - 3);
                                if (char.type === CHARACTER_TYPES.PLAYER) {
                                    logMessage(`${char.fullName}的攻击提升效果结束了`);
                                }
                            }

                            // 从状态效果中移除
                            char.statusEffects = char.statusEffects.filter(e =>
                                !(e.type === effect.type && e.duration === 0)
                            );
                        }
                    }
                });
            });
        }

        // 更新技能冷却
        function updateAbilityCooldowns() {
            gameState.characters.forEach(char => {
                if (char.abilities) {
                    char.abilities.forEach(ability => {
                        if (ability.currentCooldown > 0) {
                            ability.currentCooldown--;
                        }
                    });
                }
            });
        }

        // 检查是否所有角色都已行动
        function checkAllMoved() {
            const unmovedPlayers = gameState.characters.filter(
                char => char.type === CHARACTER_TYPES.PLAYER && !char.moved
            );

            if (unmovedPlayers.length === 0) {
                // 所有角色都已行动，自动结束回合
                setTimeout(endPlayerTurn, 1000);
            }
        }

        // 检查是否胜利
        function checkVictory() {
            const enemies = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY);

            if (enemies.length === 0) {
                // 所有敌人都被击败，胜利
                logMessage('所有敌人都被击败了！');
                showNotification('胜利！所有敌人都被击败了！');

                // 播放胜利音效
                SoundManager.play('victory');

                // 显示胜利弹窗
                showEventPopup(
                    '战斗胜利！',
                    `恭喜你击败了第${gameState.level}关的所有敌人！\n准备进入下一关吧！`,
                    [
                        {
                            text: '进入下一关',
                            action: () => {
                                hideEventPopup();
                                nextLevel();
                            }
                        },
                        {
                            text: '结束游戏',
                            action: () => {
                                hideEventPopup();
                                gameOver(true);
                            }
                        }
                    ]
                );
            }
        }

        // 检查是否失败
        function checkDefeat() {
            const players = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);

            if (players.length === 0) {
                // 所有玩家都被击败，失败
                logMessage('所有我方武将都被击败了...');
                showNotification('失败！所有我方武将都被击败了！');

                // 播放失败音效
                SoundManager.play('defeat');

                // 显示失败弹窗
                showEventPopup(
                    '战斗失败',
                    '所有我方武将都被击败了！',
                    [
                        {
                            text: '重新开始',
                            action: () => {
                                hideEventPopup();
                                initGame();
                            }
                        }
                    ]
                );

                gameState.gameOver = true;
            }
        }

        // 进入下一关
        function nextLevel() {
            gameState.level++;
            showNotification(`进入第${gameState.level}关！`);

            // 生成新地图和角色
            generateMap();
            spawnCharacters();

            // 重置玩家状态但保留属性
            const currentPlayers = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);

            // 清除所有角色
            gameState.characters = [];

            // 重新生成玩家，保留他们的属性
            const playerPositions = [
                { x: 1, y: 1 },
                { x: 2, y: 1 },
                { x: 1, y: 2 }
            ];

            // 为每个当前玩家设置新位置
            currentPlayers.forEach((player, index) => {
                player.x = playerPositions[index % playerPositions.length].x;
                player.y = playerPositions[index % playerPositions.length].y;
                player.moved = false;

                // 每关结束恢复部分生命值
                const healAmount = Math.floor(player.maxHp * 0.3);
                player.hp = Math.min(player.maxHp, player.hp + healAmount);

                gameState.characters.push(player);
            });

            // 重新生成敌人
            const enemyCount = Math.max(GAME_CONFIG.enemyCount, Math.floor(gameState.level / 2) + 2);
            const enemyPositions = [];

            while (enemyPositions.length < enemyCount) {
                const x = 7 + Math.floor(Math.random() * 3);
                const y = 7 + Math.floor(Math.random() * 3);

                if (!enemyPositions.some(pos => pos.x === x && pos.y === y)) {
                    enemyPositions.push({ x, y });
                }
            }

            // 敌人类型池
            const enemyTypes = [
                { names: ['曹', '曹操'], color: 'bg-red-500' },
                { names: ['夏侯', '夏侯惇'], color: 'bg-orange-500' },
                { names: ['典', '典韦'], color: 'bg-red-700' }
            ];

            if (gameState.level > 3) {
                enemyTypes.push(
                    { names: ['许', '许褚'], color: 'bg-red-600' },
                    { names: ['张', '张辽'], color: 'bg-indigo-600' }
                );
            }

            if (gameState.level > 5) {
                enemyTypes.push(
                    { names: ['吕', '吕布'], color: 'bg-purple-600' } // 更强的精英敌人
                );
            }

            for (let i = 0; i < enemyCount; i++) {
                const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
                const levelBoost = (gameState.level - 1) * 10;
                const isElite = enemyType.names[1] === '吕布' || (gameState.level > 2 && Math.random() < 0.2);
                const eliteBoost = isElite ? 20 : 0;

                // 获取角色技能
                const abilities = ABILITIES[enemyType.names[1]] ?
                    ABILITIES[enemyType.names[1]].map(ability => ({
                        ...ability,
                        currentCooldown: 0
                    })) : [];

                gameState.characters.push({
                    id: `enemy-${i}`,
                    type: CHARACTER_TYPES.ENEMY,
                    name: enemyType.names[0],
                    fullName: enemyType.names[1],
                    color: enemyType.color,
                    x: enemyPositions[i].x,
                    y: enemyPositions[i].y,
                    hp: 80 + levelBoost + eliteBoost,
                    maxHp: 80 + levelBoost + eliteBoost,
                    attack: 8 + Math.floor(levelBoost / 3) + (isElite ? 5 : 0),
                    defense: 3 + Math.floor(levelBoost / 5) + (isElite ? 3 : 0),
                    isElite: isElite,
                    abilities: abilities,
                    statusEffects: []
                });
            }

            // 重置回合状态
            gameState.turn = 'player';
            document.getElementById('turn-indicator').textContent = '玩家回合';
            document.getElementById('turn-indicator').classList.remove('bg-red-500');
            document.getElementById('turn-indicator').classList.add('bg-primary');

            // 重新渲染
            renderMap();
            updateGameInfo();

            logMessage(`进入第${gameState.level}关！敌人变得更强了！`);
        }

        // 游戏结束
        function gameOver(isVictory) {
            gameState.gameOver = true;

            if (isVictory) {
                showEventPopup(
                    '游戏胜利！',
                    `恭喜你成功通过了${gameState.level}关！`,
                    [
                        {
                            text: '再玩一次',
                            action: () => {
                                hideEventPopup();
                                initGame();
                            }
                        }
                    ]
                );
            } else {
                showEventPopup(
                    '游戏结束',
                    '很遗憾，你失败了。',
                    [
                        {
                            text: '再试一次',
                            action: () => {
                                hideEventPopup();
                                initGame();
                            }
                        }
                    ]
                );
            }
        }

        // 更新关卡进度
        function updateLevelProgress() {
            const totalEnemies = GAME_CONFIG.enemyCount + Math.floor(gameState.level / 2);
            const remainingEnemies = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY).length;
            const defeatedEnemies = totalEnemies - remainingEnemies;

            gameState.levelProgress = Math.min(100, Math.floor((defeatedEnemies / totalEnemies) * 100));

            document.getElementById('level-progress').style.width = `${gameState.levelProgress}%`;
            document.getElementById('progress-text').textContent = `${gameState.levelProgress}%`;
            updateEnemyCount();
        }

        // 更新敌人数量显示
        function updateEnemyCount() {
            const enemyCount = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY).length;
            document.getElementById('enemy-count').textContent = enemyCount;
        }

        // 更新游戏信息
        function updateGameInfo() {
            document.getElementById('level').textContent = gameState.level;
            updateLevelProgress();
        }

        // 显示信息
        function showInfo(text) {
            document.getElementById('selected-info').innerHTML = text;
        }

        // 显示通知
        function showNotification(message) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.classList.add('show');

            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }

        // 记录日志
        function logMessage(message) {
            const logContainer = document.getElementById('game-log');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.innerHTML = `<span class="text-gray-500">[${timestamp}]</span> ${message}`;

            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight; // 滚动到底部
        }

        // 随机数生成器（确保地图生成的一致性）
        function mulberry32(seed) {
            return function () {
                seed += 0x6D2B79F5;
                let t = seed;
                t = Math.imul(t ^ t >>> 15, t | 1);
                t ^= t + Math.imul(t ^ t >>> 7, t | 61);
                return ((t ^ t >>> 14) >>> 0) / 4294967296;
            }
        }

        // 初始化游戏
        window.addEventListener('load', initGame);
    </script>
</body>

</html>